如何调试gettext在PHP中不起作用?

我正在尝试在php 5.5中使用php gettext扩展(在win2008服务器上,使用IIS7)。我正在这样做:

<?php

$locale = "es";
if (isSet($_GET["locale"])) $locale = $_GET["locale"];
putenv("LC_ALL=$locale");
setlocale(LC_ALL, $locale);
bindtextdomain("messages", "./locale");
textdomain("messages");

echo gettext("Hello world");

?>

使用此文件夹结构后:

locale/es/LC_MESSAGES/messages.mo

但它总是只返回Hello world,而不是正确的翻译,目前(基于我缺乏西班牙语技能)在messages.po文件中是这样的:

msgid ""
msgstr ""
"Project-Id-Version: TestXlations\n"
"POT-Creation-Date: 2014-04-19 08:15-0500\n"
"PO-Revision-Date: 2014-04-19 09:18-0500\n"
"Language-Team: \n"
"Language: es\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 1.6.3\n"
"X-Poedit-Basepath: .\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SearchPath-0: c:/dev\n"

msgid "Hello world"
msgstr "Hola World"

这从cmd行和通过IIS失败。因此,我看到gettext调用等并执行它,但它没有读取翻译文件。我该如何进一步调试?即使删除翻译文件,我也会得到相同的行为。


答案 1

您应该检查返回值并知道哪个函数失败。它不是特定于i18n的,但对于任何PHP脚本或任何编程语言调试都很有用。

<?php
$locale = 'es';
if (isset($_GET["locale"])) $locale = $_GET["locale"];

$domain = 'messages';

$results = putenv("LC_ALL=$locale");
if (!$results) {
    exit ('putenv failed');
}

// http://msdn.microsoft.com/en-us/library/39cwe7zf%28v=vs.100%29.aspx
$results = setlocale(LC_ALL, $locale, 'spanish');
if (!$results) {
    exit ('setlocale failed: locale function is not available on this platform, or the given local does not exist in this environment');
}

$results = bindtextdomain($domain, "./locales");
echo 'new text domain is set: ' . $results. "\n";

$results = textdomain($domain);
echo 'current message domain is set: ' . $results. "\n";

$results = gettext("Hello world");
if ($results === "Hello world") {
    echo "Original English was returned. Something wrong\n";
}
echo $results . "\n";

答案 2

您是否在“locale -a”的输出中找到“es”?如果没有,则需要运行以下命令。

 sudo locale-gen es

推荐