Michal Čihař - Multi language site with PHP and gettext

Multi language site with PHP and gettext

As announced yesterday, I started to translate my website to Czech. I take it mostly as experiment how to do such thing easily. I don't want ot maintain different pages for each language, so the logical step seemed to use gettext which I know for translating regullar applications.

Using gettext from PHP is quite easy. You can just follow documentation and you will get basic idea. Only tricky part was to set encoding so that messages are displayed correctly.

The whole magic that selects translation based on host name is few lines of PHP code:

$lang = 'en';
if (substr($_SERVER['HTTP_HOST'], 0, 3) == 'cz.') {
    $lang = 'cz';

    setlocale(LC_MESSAGES, 'cs_CZ.UTF-8');
    setlocale(LC_ALL, 'cs_CZ.UTF-8');
    bindtextdomain('website', 'locale');
    bind_textdomain_codeset('website', 'utf-8');
    textdomain('website');
    $_SERVER['HTTP_HOST'] = substr($_SERVER['HTTP_HOST'], 3);
}

You can see that is't just locales and gettext initialisation and cutting host name so that rest of code doesn't have to deal both possibilities.

The hardest work is to make all PHP pages use gettext instead of plain text constants and translate them. I will probably never convert whole site, but it is not needed and only parts can be translated using this approach without any additional effort.