如何使用PHP从$ _SERVER ['HTTP_ACCEPT_LANGUAGE']获取语言值? [英] How to get the language value from $_SERVER['HTTP_ACCEPT_LANGUAGE'] using PHP?

查看:379
本文介绍了如何使用PHP从$ _SERVER ['HTTP_ACCEPT_LANGUAGE']获取语言值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?php
$language = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
echo $language;
?>

当我使用Firefox测试这段代码时,我得到 en- us,en; q = 0.7,ja; q = 0.3

When I use Firefox to test this block of code, I get en-us,en;q=0.7,ja;q=0.3,

当我使用IE测试代码块时,我得到 zh-cn

when I use IE to test the block of code, I get zh-cn.

值是 $ _ SERVER ['HTTP_ACCEPT_LANGUAGE'] 一个字符串?如何确定首选语言是中文还是日文?如何编写正则表达式以从 $ _ SERVER ['HTTP_ACCEPT_LANGUAGE'] 的值中获取语言?

Is the value of $_SERVER['HTTP_ACCEPT_LANGUAGE'] a string? How to determine whether the preferred language is Chinese or Japanese? How can I write a regular expression to get the language from the value of $_SERVER['HTTP_ACCEPT_LANGUAGE']?

推荐答案

是的, $ _ SERVER ['HTTP_ACCEPT_LANGUAGE'] 的值是一个字符串 - 参见 $ _ SERVER

Yes, the value of $_SERVER['HTTP_ACCEPT_LANGUAGE'] is a string -- see $_SERVER.

其内容由浏览器发送 - 这解释了为什么根据您使用的浏览器得到不同的结果:很可能,您的Firefox配置为请求英文页面(高优先级)或日语(低优先级),而您的IE配置为请求中文页面。

Its content is sent by the browser -- which explains why you get different results depending on the browser you are using : most likely, your Firefox is configured to request pages in english (high priority) or japanese (low priority), while your IE is configured to request pages in chinese.

这是因为HTTP标头可以包含:

This is because that HTTP header can contain :


  • 语言列表

  • optionnaly,区域代码

  • 具有相关优先级。

服务器应该使用语言进行响应ge适合用户要求的最佳。

The idea being that the server should respond, using the language that suits "the best" what's requested by the user.



关于解析该标题,这篇博文可能是一个有趣的读物: 解析接受语言以检测用户的语言

有一部分代码用于解析该HTTP头 - 它会生成一个类似于(引用)的数组

There is a portion of code proposed to parse that HTTP header -- and it generates an array that looks like this (quoting) :

Array
(
    [en-ca] => 1
    [en] => 0.8
    [en-us] => 0.6
    [de-de] => 0.4
    [de] => 0.2
)

这是一系列语言,按优先级排序,按降序排列 - - 这可能是你想要的。

Which is an array of languages, sorted by priority, in descending order -- which is probably what you want.

这篇关于如何使用PHP从$ _SERVER ['HTTP_ACCEPT_LANGUAGE']获取语言值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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