問題描述
如何通過 PHP 檢查用戶瀏覽器的語言?
How can I check the language of user's browser by PHP?
我需要為美國和英國的用戶顯示不同的頁面.
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');
?>
我為美國和英國的人們運行了一個特定的代碼.
I run a specific code for people in US and for them in UK.
推薦答案
可能只是區(qū)分大小寫的問題;eregi('en-us') 或 preg_match('/en-us/i') 應該已經找到了.
Likely just a case sensitivity issue; eregi('en-us') or preg_match('/en-us/i') should have picked it up.
但是,有時僅在標題中查找en-us"可能會出錯,尤其是當同時列出美國和英國語言時.Accept-Language"實際上是一個相當復雜的標題,您確實需要一個合適的解析器.
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,整個工作已經為你完成: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 標頭;這完全是假的.User-Agent 沒有被強制要求在任何特定的地方保存語言值,對于某些瀏覽器(例如 Opera 和一些我從未聽說過的名為Internet Explorer"的小瀏覽器),它根本不會.它確實包含一種語言,這將是瀏覽器構建所使用的語言,而不是您應該查看的用戶首選語言.(此設置將默認為構建語言,但用戶可以通過首選項 UI 進行自定義.)
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.)
這篇關于通過 PHP 檢查瀏覽器的語言?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!