gosho_ot_pochivka gosho_ot_pochivka - 3 months ago 13
Ini Question

Best way to manage text displayed to users in PHP

Ok for sure this has been asked and answered already but i somehow can't find a proper tutorial.
I want to keep the text displayed to users somewhere else and to prevent my code from becoming too large and unreadable.
My site won't be internationalized. I just want to have some kind of file with key-value structure and get the text from there. I want to keep the text in files, not in the database as some tutorials suggest.
I found a solution which will work but i am not sure whether this is a good approach.
I am thinking of using parse_ini_file and to keep my texts in .ini file. Is there something wrong with this approach? Could you suggest something better?

Answer

I put all language data in arrays. Its easy and also we can add multi-language support

lang/en.php

<?php 
 return array(  
   'index' => 'Homepage',
   'feedback' => 'Feedback'
   'logout' => 'Logout from profile',
 )
?>

lang/ru.php

<?php 
 return array(
   'logout' => 'Выйти из профиля',
 )
?>

Then we can load languages:

$lang = include('lang/en.php');
if(isset($_GET['lang']))
{
   $lang = array_merge($lang, include('lang/ru.php'));
}

After all it $lang will look like:

Array
(
   [index] => Homepage
   [feedback] => Feedback
   [logout] => Выйти из профиля
)

And we can very simple use it:

function __($name) {
    global $lang;
    return $lang[$name];
}

Somewhere in the site template:

...
<title><?=__('index')?></title>
</head>
<body>
<?=__('feedback')?>