問題描述
如何通過(guò) PHP 檢查用戶瀏覽器的語(yǔ)言?
How can I check the language of user's browser by PHP?
我需要為美國(guó)和英國(guó)的用戶顯示不同的頁(yè)面.
I need to show a different page for people in US and in UK.
我嘗試了以下代碼失敗
<?php
if(ereg("us", $_SERVER["HTTP_ACCEPT_LANGUAGE"]))
include('http://page.com/us.txt');
else
include('http://page.com/uk.txt');
?>
我為美國(guó)和英國(guó)的人們運(yùn)行了一個(gè)特定的代碼.
I run a specific code for people in US and for them in UK.
推薦答案
可能只是區(qū)分大小寫的問題;eregi('en-us') 或 preg_match('/en-us/i') 應(yīng)該已經(jīng)找到了.
Likely just a case sensitivity issue; eregi('en-us') or preg_match('/en-us/i') should have picked it up.
但是,有時(shí)僅在標(biāo)題中查找en-us"可能會(huì)出錯(cuò),尤其是當(dāng)同時(shí)列出美國(guó)和英國(guó)語(yǔ)言時(shí).Accept-Language"實(shí)際上是一個(gè)相當(dāng)復(fù)雜的標(biāo)題,您確實(shí)需要一個(gè)合適的解析器.
However, just looking for ‘en-us’ in the header may get it wrong sometimes, in particular when both the US and UK languages are listed. "Accept-Language" is actually quite a complicated header, which really you'd want a proper parser for.
如果你有 PECL,整個(gè)工作已經(jīng)為你完成:http://www.php.net/manual/en/function.http-negotiate-language.php
If you have PECL the whole job is already done for you: http://www.php.net/manual/en/function.http-negotiate-language.php
我不知道為什么其他答案都用于 User-Agent 標(biāo)頭;這完全是假的.User-Agent 沒有被強(qiáng)制要求在任何特定的地方保存語(yǔ)言值,對(duì)于某些瀏覽器(例如 Opera 和一些我從未聽說(shuō)過(guò)的名為Internet Explorer"的小瀏覽器),它根本不會(huì).它確實(shí)包含一種語(yǔ)言,這將是瀏覽器構(gòu)建所使用的語(yǔ)言,而不是您應(yīng)該查看的用戶首選語(yǔ)言.(此設(shè)置將默認(rèn)為構(gòu)建語(yǔ)言,但用戶可以通過(guò)首選項(xiàng) UI 進(jìn)行自定義.)
I don't know why the other answers are going for the User-Agent header; this is utterly bogus. User-Agent is not mandated to hold a language value in any particular place, and for some browsers (eg. Opera, and some minor browser I've never heard of called ‘Internet Explorer’) it will not at all. Where it does contain a language, that'll be the of language the browser build was installed in, not the user's preferred language which is what you should be looking at. (This setting will default to the build language, but can be customised by the user from the preferences UI.)
這篇關(guān)于通過(guò) PHP 檢查瀏覽器的語(yǔ)言?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!