Php-使网站多语言与代码的微小变化


Php - make site multilangue with minumum changes of code

我有用php编码的站点。它使用类似的结构

print "$x $y at {$SERVER['HTTP_HOST']}";

现在我想让我的网站多语言,但我想在代码中使用最少的更改,以便能够编写类似的东西

//my translation array - I select all such lines in one place
//IMPORTANT: $x, $y and $SERVER['HTTP_HOST'] are not defined yet. 
//This templates should be defined before the code.
$lang = array(
    'message'=>'$x $y at {$SERVER['HTTP_HOST']}';
);
translate('message');

它将翻译我的网站。

这是更多的伪代码,说明了我的想法:

<?php
error_reporting(E_ALL);
///////////////////////translation
//my translation array. 
//IMPORTANT: $x, $y and $SERVER['HTTP_HOST'] are not defined yet.
//This templates should be defined before the code.
$_SERVER['HTTP_HOST']=='localhost';
$lang = array(
    'message'=>"$x $y at {$_SERVER['HTTP_HOST']}",
);
function translate($v){
    //hmmm. All magic is doing here - but I do not know how :)
    global $lang;
    $tpl = $lang[$v];
    print $tpl;
    eval("'$tpl = '"$tpl'";");
    print $tpl;
}

////////////////////////start main work
$x = 'hello';
$y = 'world';
print $lang['message'];
translate("message");
//I want to print "hello world at localhost";
$y = 'world2';
translate("message");
//I want to print "hello world2 at localhost";
$lang['message'] = 'only $x';
translate("message");
//I want to print "only hello";
?>

但它不起作用:)

如何可能实施这种方法?

不是很好,但只需最少的初始努力即可完成您想要的:

$lang = array(
    'en'=>"$x $y at {$_SERVER['HTTP_HOST']}",
    'it'=>"$x $y italiano {$_SERVER['HTTP_HOST']}",
    // whatever other language
);
function translate($v, array $lang){
    if (array_key_exists($v, $lang)) {
        return $lang[$v];
    } else {
        throw new Exception('Invalid language');
    }
}
echo translate('it', $lang);

我想说,如果你想扩展翻译功能,那么按照你的建议,使用内联php数组进行翻译会导致一片混乱。

我使用的基本方法如下:

1) 保留一个"翻译"表,它看起来像

Keyword | English | German | ...
hello   | hello   | hallo  | ...

2) 然后在页面加载时,从DB中获取它们,并创建一个翻译数组,如下所示:

$translate = array(
    'hello'=> array ("English"=>"hello", "German"=>"hallo"),
    'next_translation'=> array ("English"=>"...", "German"=>"..."),
    ....
);

3) 使用当前语言维护$lang变量,即"英语"。

4) 因此,每当你需要翻译某个东西时,你只需要密钥和语言变量:

$translate[$keyword][$lang];