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

标签 php frameworks internationalization gettext

我一直听说 gettext - 我知道它是某种 unix 命令,用于根据提供的字符串参数查找翻译,然后生成一个 .pot 文件,但有人可以通俗易懂地向我解释这是如何进行的在 Web 框架中处理?

我可能会看看一些已建立的框架是如何做到的,但外行人的解释会有所帮助,因为它可能有助于在我真正深入研究以提供我自己的解决方案之前更清楚地了解情况。

最佳答案

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

查找键是“基础”语言中的句子。

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

echo _("Hello, world!");

对于每种语言,您都会有一个包含 key 和翻译版本的相应文本文件(注意 %s 可以与 printf 函数一起使用)

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"

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

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

locale/de_DE/LC_MESSAGES/myPHPApp.mo

locale/zh_CN/LC_MESSAGES/myPHPApp.mo

locale/it_IT/LC_MESSAGES/myPHPApp.mo

然后你的php脚本必须设置需要使用的locale

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");
?>

总是从php手册看here一个好的教程

关于php - 使用 gettext 在 PHP 中添加对 i18n 的支持?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1192665/

相关文章:

php - 是否可以在 Dreamweavers 动态表格向导中更改动态表格布局?

php - 了解 "post/redirect/get"模式

php - MySQL REST API 服务器上的连接过多 (PHP Yii2)

PHP 按时间对数组进行排序并找到与 X 数字最接近的匹配项

c# - .NET 5.0 或 .NET Framework 3.5 用于在 Windows 7+ 上部署?

frameworks - IDE和Framework之间的区别

java - 如何使用 java 接口(interface)在外部提供实现

ruby-on-rails - 带有语言环境的 Ruby on Rails 路由

android:以编程方式本地化动态字符串

ruby-on-rails - 有没有一种 Rails 方法可以翻译模型名称以用于标题(即 titleize?)