使用gettext在PHP中添加对i18n的支持?

med*_*iev 5 php frameworks gettext internationalization

我一直听说过gettext - 我知道这是基于提供的字符串参数查找翻译的某种unix命令,然后生成一个.pot文件,但有人可以用外行的方式向我解释如何处理这个问题.一个网络框架?

我可能会考虑一些已建立的框架是如何做到的,但外行人的解释会有所帮助,因为它可能有助于在我真正钻研事物以提供我自己的解决方案之前更清楚一点.

yan*_*kmm 12

gettext系统回显一组二进制文件中的字符串,这些二进制文件是从包含同一句子的不同语言的翻译的源文本文件创建的.

查找键是"基础"语言中的句子.

在你的源代码中你会有类似的东西

echo _("Hello, world!");
Run Code Online (Sandbox Code Playgroud)

对于每种语言,您将拥有一个带有密钥和翻译版本的相应文本文件(请注意可以与printf函数一起使用的%s)

french
msgid "Hello, world!"
msgstr "Salut, monde!"
msgid "My name is %s"
msgstr "Mon nom est %s"

italian
msgid "Hello, world!"
msgstr "Ciao, mondo!"
msgid "My name is %s"
msgstr "Il mio nome è %s"
Run Code Online (Sandbox Code Playgroud)

这些是您创建本地化所需的主要步骤

  • 你的所有文本输出都必须使用gettext函数(gettext(),ngettext(),_())
  • 使用xgettext(*nix)来解析你的php文件并创建基本.po文本文件
  • 使用poedit将翻译文本添加到.po文件中
  • 使用msgfmt(*nix)从.po文件创建二进制.mo文件
  • 把.mo文件放在像这样的目录结构中

区域设置/ de_DE这个/ LC_MESSAGES/myPHPApp.mo

区域设置/的en_EN/LC_MESSAGES/myPHPApp.mo

区域设置/ it_IT/LC_MESSAGES/myPHPApp.mo

那么你的php脚本必须设置需要使用的语言环境

php手册中的示例对于该部分非常清楚

<?php
// Set language to German
setlocale(LC_ALL, 'de_DE');

// Specify location of translation tables
bindtextdomain("myPHPApp", "./locale");

// Choose domain
textdomain("myPHPApp");

// Translation is looking for in ./locale/de_DE/LC_MESSAGES/myPHPApp.mo now

// Print a test message
echo gettext("Welcome to My PHP Application");

// Or use the alias _() for gettext()
echo _("Have a nice day");
?>
Run Code Online (Sandbox Code Playgroud)

总是从PHP手册看这里一个很好的教程