4

我正在做一个小项目,包括后端的注册、登录、密码重置和用户管理。我必须为不同的语言创建翻译文件,而不是使用 gettext 之类的东西(我对此一无所知),我决定为每个语言文件使用一个静态数组来实现一个非常简单的方法,如下所示:

function plLang($phrase) {
    $trimmed = trim($phrase);
    static $lang = array(
    /* -----------------------------------
    1. REGISTRATION HTML
    ----------------------------------- */
    'LNG_1'     => 'some text',
    'LNG_2'     => 'some other text',
    etc. ...
    );

    $returnedPhrase = (!array_key_exists($trimmed,$lang)) ? $trimmed : $lang[$trimmed];
    echo $returnedPhrase;
}

它工作正常,在这个阶段非常快,但我的标记现在到处都是 php 语言标签,我不确定我是否做出了正确的决定。我以前从未这样做过,所以我不知道我在期待什么。似乎当我全部完成时,这个文件将有一英里长。

这是这样做的好方法吗?你有没有更好的方法可以建议?

谢谢!

4

3 回答 3

8

这就是我在我的 cms 中所做的:

  • 对于each我开发的插件/程序/实体(你命名它),我创建一个/translations文件夹。
  • 我把我所有的翻译都放在那里,命名为el.txt、de.txt、uk.txt等。所有语言
  • 我将翻译数据存储在JSON中,因为它易于存储、易于阅读并且每个人都最容易发布他们的。
  • files can be easily UTF8 encoded in-file without messing with databases, making it possible to read them in file-mode. (just JSON.parse them)
  • on installation of such plugins, i just loop through all translations and put them in database, each language per table row. (etc. a data column of TEXT datatype)
  • for each page render i just query once the database for taking this row of selected language, and call json_decode() to the whole result to get it once; then put it in a $_SESSION so the next time to get flash-speed translated strings for current selected language.

the whole thing was developed having i mind both performance and compatibility.

in your case a row in such file could be like:

in en.txt

{"id":"LNG_1","str":"My word"}

in de.txt

{"id":"LNG_1","str":"Mein Wort"}

The current language could be stored in session like $_SESSION["language"]; and use that as starting point. Then, you can read translations like:

lang("LNG_1");
于 2012-06-10T20:05:12.607 回答
2

Many frameworks store those language-arrays in separate files, wherein each array in any language has the same name. Your language-function then just requires the appropriate file for the user-selected language (require('lang.en.php')).

// lang.en.php
$languageStrings = array(
    'login' => 'Log in',
);

// lang.ru.php
$languageStrings = array(
    'login' => 'Авторизовать в системе',
);

// lang.ja.php
$languageStrings = array(
    'login' => 'ログイン',
);

Which language currently is in use (e.g. selected by the user), can be determined via some globally accessible variable.

Idea: Use IETF language tags as language keys.

于 2012-06-10T20:39:07.917 回答
0

您应该使用支持国际化的模板引擎。
例如,我自己的模板引擎允许我执行以下操作:

<p>(_text to be localized here)</p>

并且该标记内的文本将被翻译。这样可以避免每次打开模板文件中的 php 标签,例如:

<p><?php plLang('lang'); ?></p>

无论如何,标准解决方案是使用 gettext http://php.net/manual/en/book.gettext.php

例子:

// alias _() for gettext()
echo _("Have a nice day");
于 2012-06-10T18:45:51.073 回答