PHP:多语言问题 [英] PHP :multi-language issue

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

问题描述

我正在创建一个多语言站点,语言切换器会加载所需的语言文件,但如果该文件不包含所需的条目,则它根本不会出现,甚至默认数组值也不可见.

I am creating a multilingual site, language switcher loads needed language file but if the file doesn't contain the needed entry, it doesn't appear at all, even default array value is not visible.

我是这样翻译的:

$lang = "en";
if(isset($_GET['lang'])){ 
    $lang = $_GET['lang']; 
}
require_once("languages/lang_".$lang.".php");

语言数组:

<?php echo $language["USERNAME"]; ?>

带翻译的语言文件:

$language["USERNAME"] = "User name";

如果语言文件不包含$language["USERNAME"] = "User name";那么什么都没有显示.我想要实现的是:如果加载的语言文件不包含翻译,则数组应返回默认值,例如:USERNAME.

If language file doesn't include $language["USERNAME"] = "User name"; then nothing is showing at all. What I am trying to achieve is: if loaded language file doesn't contain the translation, then array should return the default value, example: USERNAME.

我确实检查了数组键或值是否可用于显示所需信息,但似乎检查是在加载的语言文件中完成的,如果语言文件为空,则没有可显示的内容.我只需要显示位于主 PHP 文件中的默认数组值.如果数组没有翻译

I did check if array key or value is available to show needed information, but seems check is done in loaded language file and if the language file is empty, then there is nothing to show. I just need to show default array value which is located in the main PHP file. If there is no translation for array

<?php echo $language["USERNAME"]; ?> 

我想回显括号中的值:USERNAME.

I want to echo value in brackets: USERNAME.

推荐答案

为此,您需要定义默认语言.在这种情况下,我选择英语.

For that you need to define a default language. In that case i choose English.

在您的语言文件中,尽量不要定义变量,而是返回翻译数组.

In your language files, try not define a variable, but return the translation array.

如果您在语言文件中使用 return 关键字,您可以控制变量,因此您可以在脚本中包含多个语言文件.

If you are using return keyword in language files you can have control about variables, so you can include multiple language files in your script.

语言文件

lang_en.php

<?php
   return [
       'username' => 'username'
   ];

其他语言文件的方法相同.

the same way for the other language files.

index.php

<?php
$lang = "en" // that's default language key
$GLOBALS['defaultLanguage'] = require_once('lang_'.$lang.'.php');

if(isset($_GET['lang'])){
   $lang = $_GET['lang'];
}
$GLOBALS['language'] = include('lang_'.$lang.'.php');

if(!is_array($GLOBALS['language']) {
   $GLOBALS['language'] = [];
}
echo translate('username');

翻译功能

/**
 * @param string $key
 * @return string
 */
function translate($key)
{
    $language = $GLOBALS['language'];
    $defaultLanguage = $GLOBALS['defaultLanguage'];

    if(!isset($language[$key]) || !$language[$key]){
        $language[$key] = $defaultLanguage[$key];
    }


    return $language[$key];
}

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

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