首页 > 解决方案 > 在 php 中对多语言站点使用 Gettext 不起作用

问题描述

我正在尝试在 PHP 中使用gettext.

我正在使用 PHP7.1(无法升级),并且在我的php.ini中启用了gettext.so

见:http ://corbeauperdu.ddns.net/phpinfo.php

我已经阅读了文档并遵循了示例,但由于某种原因,它根本不会翻译成我的法语。

我的PO文件和test.php文件如下:

/prestadesk/include/locales/fr/LC_MESSAGES/prestadesk.po:
msgid ""
msgstr ""
"Language: fr\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"

msgid "This page will show the dashboard"
msgstr "Cette page affichera le tableau de bord"


/prestadesk/templates/test.php:
<?php
$lang='fr';
$domain = 'prestadesk';
$codeset = 'UTF-8';
$locales_dir = '../include/locales'; // need to go up on directory from here to get into the include/locales

// here we define the global system locale given the found language
putenv('LANG='.$lang);

// this might be useful for date functions (LC_TIME) or money formatting (LC_MONETARY), for instance
setlocale(LC_ALL, $lang);

// this will make Gettext look for $locales_dir/<lang>/LC_MESSAGES/prestadesk.mo
bindtextdomain($domain, $locales_dir);

// indicates in what encoding the file should be read
bind_textdomain_codeset($domain, $codeset);

// here we indicate the default domain the gettext() calls will respond to
textdomain($domain);

// test translate
echo gettext("This page will show the dashboard");
?>

标签: phpgettext

解决方案


好吧,我发现了问题:

网站所在的服务器需要为所需的 $lang 安装语言环境!

在服务器上,使用以下命令检查已安装的语言环境:

locale -a

如果未列出所需的语言环境,则必须编辑/etc/locale.gen并取消注释。例子:

fr_FR.UTF-8 UTF-8 
fr_FR ISO-8859-1
fr_FR@euro ISO-8859-15

然后,生成并安装该语言环境:

sudo locale-gen

完成此操作后,您将能够正确使用 gettext() 。


推荐阅读