如何使用 PHP 使网站多语言化?

How make a website multi-language using PHP?

我做了一些研究,希望通过 PHP5 使我的网站支持多种语言,但我找不到任何东西。那么有人知道如何让您的网站支持多语言吗?

一个简单的方法是使用多个文件,其中一些是语言文件,保存带有语言键的数组。像

lang_LANGCODE.php

$language = array (
    "someMessageID" => "The visible text of the id",
    "anotherMessage" => "The visible text of another message",
);

并将其余消息添加到同一个数组中,参见 Array Documentation

然后在你的 PHP 文件中你会做类似

if ($languageid ==  "english") {
    include("path/to/lang_en.php");
}elseif($languageid == "spanish"){
    include("path/to/lang_es.php");
}elseif($languageid == "other supported") {
    //Do the same with the rest of languages
}else{
    // Always load a default language file if the requested language don't exist
    include("path/to/lang_en.php");
}

要使用消息,您应该在代码中使用 $language['messageID']

如果您想获取用户语言,您可以尝试获取您支持的语言之一是否在 Accept-Language header 的数组中。否则,您可以简单地询问它并将其保存在 cookie、数据库或 session 变量中。

确保您的所有文件中都有所有字符串,否则可能会出现空字符串和错误。有一些方法可以做回退,但它有点复杂。

您也可以在语言文件中进行所有检查并有条件地定义数组,而不是有条件地包含一个文件,但是如果您有很多消息,最好阅读单独文件中的语言字符串。