lorenw
December 16, 2010, 10:06pm
1
Hi all,
I am googling and have found three different ways to implement it.
Is there a preferred way to do this?
#1
$_lang = array(
'login' => 'Login',
'password' => 'Password',
'welcome' => 'Welcone To The Website1'
);
echo $_lang['welcome'];
#2
function lang($phrase){
static $_lang = array(
'login' => 'Login',
'password' => 'Password',
'welcome' => 'Welcone To The Website2'
);
return $_lang[$phrase];
}
echo lang('welcome');
#3
define('LOGIN','Login');
define('PASSWORD','Password');
define('WELCOME','Welcome to the web site3');
echo WELCOME;
At this point I don’t have a clue as to which method to use and was hoping that someone could point me in the best practice to use.
Thanks.
To be honest IMO I personally think that a slightly different version of #1 is better. For example:
$lang["login"] = "Login";
$lang["site_header"] = "Welcome to the website!";
My reasoning is:
very easy to read even for a non developer - for example a translator
very easy to implement, just change the $lang variable and include and its done:
$lang = "en-us";
require "locale/".$lang.".php";
small file with no “logic” in it (unlike having the function lang() in every language file)
I much prefer to use INI files.
Many languages support parsing and rewriting of INI files, including PHP, so you can modify settings via a control panel rather than manually.
That’s the storage part.
PHP parses the ini file using Parse_Ini_File, and would be set as a property of a language object as an array. The object is passed to the template files.
lorenw
December 19, 2010, 8:04pm
4
I went with #1 .
I needed to make it very user friendly for a translator.
This is the cool part. it creates the elements for a form on the fly.
foreach ($_lang as $key => $value){
echo '
<tr>
<td>'.$key.'
</td>
<td>
<input type="text" name="'.$key.'" value="'.$value.'" size="200">
</td>
</tr>';
}
Super easy for anyone to edit. After submit, it rewrites the file.
foreach ($_POST as $key => $value){
if ($key =='action' || $key == 'Submit'){}
else {
// echo '\\''$key'\\'' => '\\''$value'\\', ';
$plang .= '\\''.$key.'\\' => \\''.$value.'\\',
';
}
}
$plang = substr("$plang", 0, -1);
$plangarr = '<?
$_lang = array('.$plang.');
?>';
$fp = fopen('en.lan', 'w');
fwrite($fp, $plangarr);
fclose($fp);
I thought it was a cool way to make language files easily editable.
It’s just a proof of concept and it does work, I need to name things differently and throw in more vars.
Thanks for the suggestions
Cheers.