For the past few days i've been struggling with php, gettext and getting my, soon to be, new website translated from danish to english.
I have my directories with my .po and .mo files set up as following:
/locale/en_US/LC_MESSAGES/
As per this tutorial: Localizing PHP web sites using gettext i added this:
$locale = "en_US";
if (isSet($_GET["locale"])) $locale = $_GET["locale"];
putenv("LC_ALL=$locale");
setlocale(LC_ALL, $locale);
bindtextdomain("messages", "./locale");
textdomain("messages");
I added a five entires in on my page:
echo _('Overskrift 1')
But when i view the page on my server, a Debian box with PHP 5.4 and gettext support enabled, nothing is translated.
I have no idea what i'm doing wrong. I'm sure it's something small, but i just can't see it. Maybe you guys have some pointers?
My .po file:
msgid ""
msgstr ""
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: POEditor.com\n"
"Project-Id-Version: Portfolio\n"
"Language: en\n"
#:
msgid "Overskrift 1"
msgstr "Headline 1"
#:
msgid "Overskrift 2"
msgstr "Headline 2"
#:
msgid "Overskrift 3"
msgstr "Headline 3"
#:
msgid "Overskrift 4"
msgstr "Headline 4"
#:
msgid "Overskrift 5"
msgstr "Headline 5"
The most typical problem is that your system does not have the locale installed you are setting. gettext is deeply integrated into the system's locale system. The locale you set with
setlocale
actually needs to be installed and/or aliased to the name you're giving it. On most systems there's, for instance, no localeja_JP
, but the localesja_JP.UTF8
and/orja_JP.eucJP
. You need tosetlocale(LC_ALL, 'ja_JP.UTF8')
in this case, justja
orja_JP
won't do.To check which locales are installed, run
locale -a
on the command line. If the locale you're looking for is not there, you need to install it. On Ubuntu and similar systems this is as easy as runningsudo locale-gen ja_JP.UTF8
.Alternative solution
Some rare locales may not be easy to find, and hence you may not be able to install what you want. In that case, you can find a locale that is closest. For example, if there is no
ku_IQ
butku_TR
is present on the server you're hosting your app, you could use the latter instead. Make sure you rename your directory to the locale you're actually setting it to. Your texts will still be translated normally, but your regional formats like date, time, and numbers will not be displayed properly. You will have to live with that.