Using PHP Gettext Extension vs PHP Arrays in Multilingual Websites?

alexchenco picture alexchenco · Feb 23, 2010 · Viewed 9.8k times · Source

So far the only 2 good things that I've seen about using gettext instead of arrays is that I don't have to create the "greeting" "sub-array" (or whatever its called). And I don't have to create a folder for the "default language".

Are there other pros and cos of using gettext and php arrays for multilingual websites?

USING GETTEXT:

spanish/messages.po:

#: test.php:3
msgid "Hello World!"
msgstr "Hola Mundo"

index.php:

<?php echo _("Hello World!"); ?>

index.php?lang=spanish:

<?php echo _("Hello World!"); ?> turns to Hola Mundo

USING PHP ARRAYS:

lang.en.php

<?php
$lang = array(
    "greeting" => "Hello World",
);
?>

lang.es.php

<?php
$lang = array(
    "greeting" => "Hola Mundo",
);
?>

index.php:

<?php echo $lang['greeting']; ?> greeting turns to Hello World

index.php?lang=spanish

<?php echo $lang['greeting']; ?> greeting turns to Hola Mundo

(I first started with gettext, but it wasn't supported in my shared free hosting Zymic. I didn't want to use Zend_translate, I found it too complicated to my simple task, so I finally ended up using php define, but later on someone told me I should use arrays)

Answer

ingo picture ingo · Oct 8, 2010

I recommend using gettext, I am doing that in PHP for 5 years with good results.

First of all if you use echo _('my text to translate') and have no translation for it, you will see the original string in the output, which is good. Using arrays like echo $translation['were is my translation'] and there is none, you will just see nothing. but beware, using poedit and doing a echo _(''); is not a good idea, poedit uses the msgid "" for the project information which most likely you don't want to show your audience, so one must take care of not trying to translate empty strings :)

Also it's very fast and has some additional features for plurals and stuff, also poedit for example makes the life easier by having a translation db so you must not translate the same stuff over and over again, those you did already will be prefilled and marked as "check if it's right". Very comfortable.

theby middus mentioned downside that you have to compile the po file while you could easy overwrite a php-file when using arrays - well you just overwrite your mo file too, and if using poedit, it does the compiling after saving the file. So in fact you hit save and copy the file, sam as with editing a php-file.

But a real downside is, if you use mod_php. Be aware that with mod_php it is not threadsafe, though I never had any hard problems.

It's mostly just that you have to restart your apache when using mod_php or your gettext calls will fail (sometimes no translations returned, sometimes you end up with the beloved white page with no contents). But by using something like mod_itk (I believe cgi/fastcgi can do this to) you wont even have this problem no more.