PHP中多语言的实现

问题描述 投票:0回答:1

我想知道如何在PHP脚本中实现多种语言。我真的找不到任何方便的方法来完成这样的事情,以简化翻译工作。我举一个例子:

//Output looks like this:
//Where are You, Mike? It is me, Rebeca! I am waiting here for 5 hours!

//But in file it is some abomination like:
echo 'Where are You, '.$name.'? It is me, '.$name2.'! I am waiting here for '.$time.' hours!';

//Just imagine that meantime there might be different functions, included files
//and other code required to create more sentences like the above to create long text...

如果文件输出的此类文本被许多不同的变量和代码所破坏,则语言文件应如何显示?

我想出了将用户语言保持在$ _SESSION ['lang']的想法,并且在每个文件中都包含具有正确语言的文件。但是,在我尝试这样做之后,它确实看起来像这样:

//main file
echo $txt[1].$name.$txt[2].$name2.$txt[3].$time.$txt[3];

//lang file
$txt[1] = 'Where are You, ';
$txt[2] = '? It is me, ';
$txt[3] = '! I am waiting here for ';
$txt[3] = ' hours!';

它看起来很荒谬,难以理解,并且存在许多潜在的错误。试想一下,如果您是只访问lang文件的翻译者-无法翻译此类文本,对吗?应该/应该如何做不同?

php translation multilingual
1个回答
0
投票

是的,它是那样做的,但不是像您那样做的是单个单词或句子的块,否则它不会很好地翻译。

通常如何处理问题,定义模板,然后使用传递的参数调用该函数。

请参阅:https://www.php.net/manual/en/refs.international.php以获取getext等,或找到一个库。

示例:

<?php
// for each new user_where_are_you_text.. one is translated to other lang
$trans = [
    'en' => ['user_where_are_you_text' => 'Where are You, %s? It is me, %s! I am waiting here for %s hours!'],
    'fr' => ['user_where_are_you_text' => 'Où es-tu, %s? C\'est moi, %s! J\'attends ici depuis %s heures!'],
];

$name = 'Loz';
$name1 = 'Rasmus';
$time = 3;

function __($key, ...$arguments) {
    global $trans, $lang;
    return sprintf($trans[$lang][$key], ...$arguments);
}

$lang = 'en';
echo __('user_where_are_you_text', $name, $name1, $time).PHP_EOL;

$lang = 'fr';
echo __('user_where_are_you_text', $name, $name1, $time).PHP_EOL;

https://3v4l.org/4mlke

© www.soinside.com 2019 - 2024. All rights reserved.