沃梦达 / 编程问答 / php问题 / 正文

如何使用 PHP 从 $_SERVER['HTTP_ACCEPT_LANGUAGE'] 获取语言值?

How to get the language value from $_SERVER[#39;HTTP_ACCEPT_LANGUAGE#39;] using PHP?(如何使用 PHP 从 $_SERVER[HTTP_ACCEPT_LANGUAGE] 获取语言值?)

本文介绍了如何使用 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 :

  • 语言列表
  • 可选,带有区域代码
  • 具有相关的优先级.

这个想法是服务器应该使用最适合用户请求的语言来响应.

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


关于解析该标头,这篇博文可能会很有趣:Parse Accept-Language检测用户的语言

建议有一部分代码用于解析该 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'] 获取语言值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何使用 PHP 从 $_SERVER['HTTP_ACCEPT_LANGUAGE'] 获取语言值?

基础教程推荐