Search code examples
phpgettext

PHP gettext translations not getting picked up


So I scoured stackoverflow with similar problems and checked everything. I just cannot get translations to work with gettext.

I have the following file structure

locale/
    en_US/
        LC_MESSAGES/
            messages.mo
            messages.po
test.php

messages.po contains multiple messages, but only one is translated. I ran msgfmt to generate the .mo file from .po file.

#: test.php:43
msgid "Olen omena"
msgstr "I am an apple"

Trying to run test.php with the following code:

<?php

$locale = "en_US";

$results = putenv("LANG=" . $locale);

if (!$results) {
    exit ('putenv LANG failed');
}

$results = putenv("LANGUAGE=" . $locale);

if (!$results) {
    exit ('putenv LANGUAGE failed');
}
$results = setlocale(LC_MESSAGES, $locale);

if (!$results) {
    exit ('setlocale failed');
}
echo "Locale set to: $locale<br>";

$domain = 'localhost';

$results = bindtextdomain($domain, "locale/");

if (!$results) {
    exit ('bindtextdomain failed');
}

$results = bind_textdomain_codeset($domain, "ISO-8859-1");

if (!$results) {
    exit ('bind_textdomain_codeset failed');
}

$results = textdomain($domain);

if (!$results) {
    exit ('textdomain failed');
}

echo _("Olen omena");

And it prints

Locale set to: en_US
Olen omena

Apache and PHP run inside a Docker container and I checked with locale -a that en_US exists.

...
en_US
en_US.iso885915
en_US.utf8

Tried all en_US options. Tried LC_ALL and LC_MESSAGES. Tried different domains... At a loss here. What exactly is wrong?


Solution

  • Alright! I figured it out by looking at PHP.net example! Domain must be the same as the file name! If domain is set to 'localhost' file must be named 'localhost.mo'!

    Edit I did however observe strange behaviour. For whatever reason PHP keeps resetting the translation every 7th refresh and the original text pops up. Observing the network tab in chrome the initial page load is above 400 B, second is 399 until the 7th is 395:

    enter image description here

    Does PHP reset some cache every 7th reload?