Search code examples
phpgettextsetlocalephp-gettext

Gettext in PHP requires setlocale(LC_MESSAGES, NULL) to be called


When using PHP 5.5.9 on Ubuntu, gettext isn't working although everything is set up correctly.

The lines that I use to set up gettext are the following ones:

putenv('LANG=es_ES.utf8');
setlocale(LC_MESSAGES, 'es_ES');
bindtextdomain('messages', './i18n');
bind_textdomain_codeset('messages', 'UTF-8');
textdomain('messages');

This should contain everything that is needed. But gettext is always returning the default locale's strings (the ones passed in), never the correct translations.

Calling locale -a also lists all the languages that are needed, so this is set up correctly, too.

The phpinfo() proves that gettext (and also the intl extension) are installed correctly:

GetText Support = enabled
intl version = 1.1.0
ICU version = 52.1
ICU Data version = 52.1

Ubuntu has been rebooted, of course.

And, finally, the directory that was specified does also contain the required translation files for gettext.

To put it short, everything seems to be set up correctly -- but it doesn't work.

However, when I add setlocale(LC_MESSAGES, NULL); before the call to setlocale(LC_MESSAGES, 'es_ES');, gettext suddenly works.

Can someone explain this? While the OS and PHP versions aren't the latest anymore, I don't know of any bugs that prevent gettext from working on this stack.

The solution feels like a dirty hack, and certainly not something that I feel comfortable to rely on.


Solution

  • When you call setlocale(LC_MESSAGES, NULL), it uses locale name from environment, so it'll be "es_ES.utf8".

    You can try to call setlocale(LC_MESSAGES, "es_ES.utf8") instead, or even better
    setlocale(LC_MESSAGES, array("es_ES", "es_ES.utf8"))