国际化简单 PHP 网站的最佳方式

2022-01-18 00:00:00 internationalization php multilingual

我必须开发一个非常简单的 php 网站,所以我不需要框架.但它必须支持多语言(EN/FR/CHINESE).我一直在寻找系统内置的 php,我找到了两种方法:

I have to develop a pretty simple php website so I don't need framework. But it's must support multi language (EN/FR/CHINESE). I have looked for php built in system and I found two ways :

  • 来自 php5.3 的 intl 模块 (http://php.net/manual/fr/book.intl.php)
  • gettext (http://php.net/manual/fr/book.gettext.php)

我在没有框架的 i18n 方面没有经验,所以关于支持多语言的最简单方法有什么建议?

I have no experience in i18n without framework, so any advices about what's the simplest way to support multi language ?

最后我只需要一个将翻译搜索到文件的功能(按语言一个文件).情商:trans('hello');

At end I just need a function that search translation into file (one file by language). EQ : trans('hello');

=> en.yaml(yaml与否,只是一个例子)

=> en.yaml (yaml or not, it's an example)

hello: "Hello world!"

=> fr.yaml

hello: "Bonjour tout le monde !"

如果可能的话,我更喜欢纯 PHP 实现

And if possible I prefer Pure PHP implementations

推荐答案

虽然ext/gettextext/intl都和i18(国际化)有关,但gettext 处理翻译,而 intl 处理国际化的事情,如数字和日期显示、排序顺序和音译.因此,您实际上需要两者来获得完整的 i18 解决方案.根据您的需要,您可能会提出一个依赖上述扩展或您使用某些框架提供的组件的自制解决方案:

Although ext/gettext and ext/intl are both related to i18 (internationalization), gettext deals with translation while intl deals with internationalizing things like number and date display, sorting orders and transliteration. So you'd actually need both for a complete i18-solution. Depending on your needs you may come up with an home-brew solution relying on the extensions mentioned above or your use components provided by some framework:

  • 翻译
    • Symfony 2 翻译组件:https://github.com/symfony/Translation
    • Zend 框架 Zend_Translate
    • Zend 框架 Zend_Locale

    如果您只需要翻译并且网站足够简单,那么您的简单解决方案(将翻译配置文件读入 PHP 数组,使用简单函数检索令牌)可能是最简单的.

    If you only need translation and the site is simple enough, perhaps your simple solution (reading a translation configuration file into an PHP array, using a simple function to retrieve a token) might be the easiest.

    我能想到的最简单的解决方案是:

    The most simple solution I can think of is:

    $translation = array(
        'Hello world!' => array(
            'fr' => 'Bonjour tout le monde!',
            'de' => 'Hallo Welt!'
        )
    );
    
    if (!function_exists('gettext')) {
        function _($token, $lang = null) {
            global $translation;
            if (   empty($lang)
                || !array_key_exists($token, $translation)
                || !array_key_exists($lang, $translation[$token])
            ) {
                return $token;
            } else {
                return $translation[$token][$lang];
            }
        }
    }
    
    echo _('Hello World!');
    

相关文章