PHP gettext and vagrant running ubuntu

2019-01-29 03:27发布

问题:

I'm having a problem getting gettext to translate one of my translation files on my Vagrant setup running Ubuntu. My locale files are in a directory like so...

locales\de_DE\LC_MESSAGES\default.po

I am confident that the translation files are ok as I have a local version of xampp pointing to exactly the same file and it works fine.

I have tried the following and almost just want to figure out what is going on because I've spent so long looking into it

  • Permissions - I can output the content of the default.mo file on the webpage
  • Enabled locales in "/etc/locale.gen", ran "locale-gen" and restarted apache

Is there anything that I may have missed?

<?php

define('LOCALES_DIR', "../locales");

if (! file_exists(LOCALES_DIR)) {
    exit("Locales not found from here");
}

$content = file_get_contents(LOCALES_DIR . "/de_DE/LC_MESSAGES/default.mo");
if (strlen($content) < 1) {
    exit("File could not be read");
}

$language = "de_DE.UTF-8";
putenv('LANG=' . $language);
setlocale(LC_ALL, $language);

$domain = "default";
bindtextdomain($domain, LOCALES_DIR);
textdomain($domain);
bind_textdomain_codeset($domain, 'UTF-8');

echo _("Sign In");

Updates

  • For some reason it is now semi-working intermittently, on the 3rd refresh it will display the correct text.
  • My PHP versions are slightly different
    • vagrant: 5.4.42
    • local: 5.4.7
  • Not sure if it helps but the php_sapi_name() on vagrant was "fpm-fcgi" and on local it was "apache2handler", just guessing as not 100% sure on the difference but might explain why an Apache restart was not enough on vagrant

回答1:

So it turns out that following the suggestion here worked for me https://stackoverflow.com/a/20602983/682754

sudo service php5-fpm restart

I am guessing it may have stemmed from one of the following:

  • I had been switching the locale values de_DE.UTF-8 to not use the hyphen and tried lowercase, I noticed on Ubuntu it is de_DE.utf8
  • I had also changed the names of my .po and .mo files