PHP gettext 在本地 WAMP 服务器上不起作用


PHP gettext doesn't work on local WAMP server

我一直无法在本地WAMP(v2.5)服务器上运行翻译。下面是问题的示例。

putenv("LANG=frc");                          //output: 1
setlocale(LC_ALL, "frc");                    //output: French_Canada.1252
$domain = 'messages';
bindtextdomain($domain, "locale");           //output: D:'wamp'www'[project folder]'locale
bind_textdomain_codeset($domain, 'UTF-8');   //output: UTF-8
textdomain($domain);                         //output: messages
echo gettext("Hello");                       //output: Hello

这是文件夹结构:

locale
     --> French_Canada.1252
        --> LC_MESSAGES
            --> messages.po
            --> messages.mo

最后是 PO 文件:

msgid ""
msgstr ""
"Project-Id-Version: 'n"
"POT-Creation-Date: 2016-02-10 14:01-0500'n"
"PO-Revision-Date: 2016-02-10 14:01-0500'n"
"Last-Translator: 'n"
"Language-Team: 'n"
"Language: fr_CA'n"
"MIME-Version: 1.0'n"
"Content-Type: text/plain; charset=UTF-8'n"
"Content-Transfer-Encoding: 8bit'n"
"X-Generator: Poedit 1.8.2'n"
"X-Poedit-Basepath: ../../..'n"
"Plural-Forms: nplurals=2; plural=(n > 1);'n"
"X-Poedit-SearchPath-0: .'n"
#: test.php:11
msgid "Hello"
msgstr "Bonjour"

这是我尝试过的:
1) 卸载 64 位 WAMP 并在其位置安装 32 位 WAMP。
2)使用不同的语言环境代码,如fr_CA,fr_FR,fr.fr是唯一被识别的代码,但我仍然有同样的问题(即使将文件夹重命名为fr)
3) 将代码集更改为 1252 和 Windows-1252(在 php 文件和 PO 文件中)
4) 每次更改后重新启动所有服务

使用 GetText 类 : https://github.com/oscarotero/Gettext在本地或网络上以不同的方式加载您的 .po 文件。

use Gettext'Translator;
use Gettext'GettextTranslator;
$locale = !empty($_GET['locale']) ? $_GET['locale'] : Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']); 
$_SESSION['locale'] = $locale;
putenv("LC_ALL=$locale");
setlocale(LC_ALL, $locale);
$domain = 'traduction';
if(strstr($_SERVER['HTTP_HOST'], '127.0.0.1')) {
    $t = new Translator();
    //Create a Translations instance using a po file
    $translations = Gettext'Translations::fromPoFile('locale/'.$locale.'/LC_MESSAGES/'.$domain.'.po');
    $t->loadTranslations($translations);

} else {
    //Create the translator instance
    $t = new GettextTranslator();
    //Set the language and load the domain
    $t->setLanguage($locale);
    $t->loadDomain($domain, 'Locale');
}
//If you want use the global functions
$t->register();
echo __('Pomme'); // "Apple"
echo n__('%d fenetre', '%d fenetres', 2, 2); // "2 windows"