PHP中多语言的实现 [英] Implementation of multilanguage in PHP

查看:62
本文介绍了PHP中多语言的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在 PHP 脚本中实现多种语言.我真的找不到任何方便的方法来说明应该如何做这样的事情以使翻译更容易.我举个例子:

I was wondering how to implement multiple languages in PHP script. I couldn't really find any handy way of how such thing should be done to make it easy for translator. I'll give an example:

//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...

如果文件输出的文本被许多不同的变量和代码打乱,那么语言文件应该是什么样子的?

If the file outputs such text shattered by many different variables and code, how the language file should look like?

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

I came up with idea to keep the user language in $_SESSION['lang'], and in each file include file with correct language. But after I tried to do so, it does look like this:

//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 文件的翻译人员 - 不可能翻译这样的文本,对吗?这应该/可以如何做?

It looks ridiculous, unreadable, and with many potential mistakes. And just imagine if You are translator that gets access only to the lang file - it is impossible to translate such text, right? How this should/could be done differently?

推荐答案

是的,它是这样做的,但不是像你那样做的单个单词或句子块,否则它不会翻译得很好.

Yes, its done like that but not individual words or blocks of the sentence like your doing, else it would not translate well.

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

How it's generally done to handle the problem, you define your templates and then have a function which you call with passed params.

参见:https://www.php.net/manual/en/refs.international.php 用于 getext 等,或找到一个库.

see: https://www.php.net/manual/en/refs.international.php for getext etc, or find a lib.

示例:

<?php
$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/e1nEB

这篇关于PHP中多语言的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆