Is gettext the best way to localise a website in php? (only mild localisation needed)
You can just use a lang_XX.php
and include it in your application.
$lang = array(
"welcome" => "Welcome",
"bye" => "Bye"
);
For other languages, say lang_fr.php
, just have something like:
$lang = array(
"welcome" => "Accueil",
"bye" => "Au revoir"
);
For a small use case, this should be fine and no need for going with .po
files. Also, you can define it this way:
function _($l)
{
return $lang[$l];
}
gettext is the best way. For a small site with few strings that isn't expected to grow much implementing something similar to the solutions posted already may actually be quicker than learning how to use gettext and configuring it.
tl;dr:
People have been thinking hard over many years to create a translation system that works, you could spend ages re-inventing that wheel, or you could spend a little while learning how to use gettext.
In the open source world, gettext is practically a de-facto standard.
Here are some reasons why gettext is better than the usual alternative of maintaining big lists of translation arrays
- It is faster
- It does not require loading every single string into memory once per thread
- It has lots of tool support for translators, such as poedit, so you are not reliant on your translators understanding how to edit PHP code.
- It has tool support for you, msgmerge and so forth, mean you can send off your file to be translated while still working and adding new translatable text and easily merging them back together
- Need to give a comment to the translator about the context of a string? gettext will take a comment from the code where it is used and copy it to the translation file
- The translation keys are the English text, if it hasn't been translated yet then the text is still displayed in plain English, none of the solutions given on this answer to date get this right.
- It supports plurals, if a string depends upon an integer, in english there are only two forms
if n != 1 "There was a person" else "There were n people"
. For other languages the rule isn't as simple as if (n!=1), Russian has 3 different variants and the rule isn%100/10==1 ? 2 : n%10==1 ? 0 : (n+9)%10>3 ? 2 : 1;
Performance-wise, gettext
Extension is faster than using a String-Array that maps like string ids to localized text (for example "WelcomeText" => "Welcome to our homepage."
would be included using something <?= $strings["WelcomeText"] >
. The pure PHP implementation of gettext is slower and not recommended if you can use the PHP Extension. More details here Localizing PHP web sites using gettext and Benchmarking PHP Localization – Is gettext fast enough?