【问题标题】:Adding support for i18n in PHP with gettext?使用 gettext 在 PHP 中添加对 i18n 的支持?
【发布时间】:2009-07-28 08:27:32
【问题描述】:

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

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

【问题讨论】:

    标签: php frameworks internationalization gettext


    【解决方案1】:

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

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

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

    echo _("Hello, world!");
    

    对于每种语言,您都会有一个相应的文本文件,其中包含密钥和翻译版本(注意可与 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"
    

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

    • 所有文本输出都必须使用 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 脚本必须设置需要使用的语言环境

    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 手动示例似乎没有翻译给定的字符串。这个例子还有什么关系吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 2013-05-24
    相关资源
    最近更新 更多