PHP gettext function only returns original untranslated string
I'm trying to use gettext add localisation support to my website. I've followed various guides on how to s开发者_C百科etup gettext and have done the following:
I've created the following files and directories in the root of my project dir:
test.php
locale/
de_DE
LC_MESSAGES
messages.mo
messages.po
en_GB
LC_MESSAGES
messages.mo
messages.po
I've used Poedit to create the above .po and mo files. I've made sue it use Unix line endings, UTF-8 and set the language and country accordingly.
I've then created a PHP script called test.php which has the following code:
<?php
define('LOCALE', 'de_DE');
// Set up environmental variables
putenv("LC_ALL=" . LOCALE);
setlocale(LC_ALL, LOCALE);
bindtextdomain("messages", "./locale");
bind_textdomain_codeset("messages", LOCALE .".utf8");
textdomain("messages");
die(gettext('This is a test.'));
?>
I've imported the text "This is a test." to Poedit and supplied the translation and saved it.
But for some reason the test.php script will only output the original text untranslated. It refuses to load the version for the translation files.
It's worth noting that the server is running Linux (Ubuntu),
Apache 2.2.11 and PHP 5.2.6-3ubuntu4.5. I've checked phpinfo()
and gettext is enabled.
Your problem might be related to a missing locale on your system. Please install the German locale and everything should work:
sudo apt-get install language-pack-de-base
Then, issue the following command and you should see the German locales:
locale -a
After that, the following code should work, assuming you still have the .po and .mo files on the directory structure you described:
<?php
setlocale(LC_ALL, 'de_DE.UTF-8');
bindtextdomain('messages', './locale');
textdomain('messages');
echo gettext('This is a test.');
?>
Yes, yes, PHP's gettext support again. Just a hint, that might or might not be helpful to you:
Because of PHP's awful gettext implementation, many open source projects like WordPress switched to this one: http://savannah.nongnu.org/projects/php-gettext/ and completely bypass the original version.
I did it, too, in one of my projects, and I can't say that I miss anything.
Disadvantage for commercial projects: It's under the GPL.
try the following
<?php
define(LC_MESSAGES, 'de_DE');
// Set up environmental variables
putenv("LANGUAGE=de_DE");
bindtextdomain("*", dirname(__FILE__).'/locale');
bind_textdomain_codeset("messages", 'UTF-8');
die(gettext('This is a test.'));
?>
精彩评论