PHP语言检测 [英] PHP language detection

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

问题描述

我正在尝试建立多语言站点.

I'm trying to build multilangual site.

我使用这段代码来检测用户的语言.如果您尚未选择语言,它将包括基于HTTP_ACCEPT_LANGUAGE的语言文件.

I use this piece of code to detect users language. If you havent chosen a language, it will include your language file based on HTTP_ACCEPT_LANGUAGE.

我不知道从哪里得到它:

I don't know where it gets it from though:

session_start();

if (!isset($_SESSION['lang'])) {
   $_SESSION['lang'] = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
}

elseif (isset($_GET['setLang']) && $_GET['setLang'] == 'en') $_SESSION['lang'] = "en";
elseif (isset($_GET['setLang']) && $_GET['setLang'] == 'sv') $_SESSION['lang'] = "sv";
elseif (isset($_GET['setLang']) && $_GET['setLang'] == 'pl') $_SESSION['lang'] = "pl";
elseif (isset($_GET['setLang']) && $_GET['setLang'] == 'fr') $_SESSION['lang'] = "fr";

include('languages/'.$_SESSION['lang'].'.php');

它对我有用,并且包含波兰语lang文件.但是这段代码正确吗?还是有另一种方法?

It works for me and includes the polish lang file. But is this code accurate? Or is there another way?

推荐答案

浏览器通常会发送一个HTTP标头,名称为Accept-Language,它指示用户愿意使用哪种语言.

The browser generally sends a HTTP header, name Accept-Language, that indicates which languages the user is willing to get.

例如,此标头可以是:

Accept-Language: en-us,en;q=0.5

其中有优先级概念,顺便说一句;-)

There is notion of priority in it, btw ;-)

在PHP中,您可以在$_SERVER超级全局变量中获取它:

In PHP, you can get this in the $_SERVER super global :

var_dump($_SERVER['HTTP_ACCEPT_LANGUAGE']);

会让我:

string 'en-us,en;q=0.5' (length=14)

现在,您必须解析;-)

Now, you have to parse that ;-)


如果我在浏览器的选项中编辑了自己的偏好设置,说:我想要法语,并且如果您不能为我提供法语,请从美国那里获取英语;如果您也不能得到我,那么请获取我英文),标题为:


If I edit my preferences in the browser's option to say "I want french, and if you don't can't serve me french, get me english from the US ; and if you can't get me that either, just get me english), the header will be :

Accept-Language: fr-fr,en-us;q=0.7,en;q=0.3

而且,来自PHP:

string 'fr-fr,en-us;q=0.7,en;q=0.3' (length=26)


有关更多信息,请查看HTTP的第14.4节RFC .


For more informations, you can take a look at section 14.4 of the HTTP RFC.

您可能会在PHP中找到很多代码示例来解析该标头;例如:解析接受语言"以检测用户的语言

And you probably can find lots of code example in PHP to parse that header ; for instance : Parse Accept-Language to detect a user's language

玩得开心!

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

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