在PHP中检测浏览器语言我使用以下PHP脚本作为我的网站的索引。这个脚本应该包含一个特定的页面,这取决于浏览器的语言(自动检测到)。此脚本并不适用于所有浏览器,因此它总是包括index_en.php对于任何检测到的语言(问题的原因很可能是一些接受语言头没有被考虑的问题)。你能给我一个更有力的解决方案吗?<?php// Open session varsession_start();// views: 1 = first visit; >1 = second visit
// Detect language from user agent browserfunction lixlpixel_get_env_var($Var){
if(empty($GLOBALS[$Var]))
{
$GLOBALS[$Var]=(!empty($GLOBALS['_SERVER'][$Var]))?
$GLOBALS['_SERVER'][$Var] : (!empty($GLOBALS['HTTP_SERVER_VARS'][$Var])) ? $GLOBALS['HTTP_SERVER_VARS'][$Var]:'';
}}function lixlpixel_detect_lang(){
// Detect HTTP_ACCEPT_LANGUAGE & HTTP_USER_AGENT.
lixlpixel_get_env_var('HTTP_ACCEPT_LANGUAGE');
lixlpixel_get_env_var('HTTP_USER_AGENT');
$_AL=strtolower($GLOBALS['HTTP_ACCEPT_LANGUAGE']);
$_UA=strtolower($GLOBALS['HTTP_USER_AGENT']);
// Try to detect Primary language if several languages are accepted.
foreach($GLOBALS['_LANG'] as $K)
{
if(strpos($_AL, $K)===0)
return $K;
}
// Try to detect any language if not yet detected.
foreach($GLOBALS['_LANG'] as $K)
{
if(strpos($_AL, $K)!==false)
return $K;
}
foreach($GLOBALS['_LANG'] as $K)
{
//if(preg_match("/[[( ]{$K}[;,_-)]/",$_UA)) // matching other letters (create an error for seo spyder)
return $K;
}
3 回答
梦里花落0921
TA贡献1772条经验 获得超6个赞
你为什么不保持简单干净呢?
<?php $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); $acceptLang = ['fr', 'it', 'en']; $lang = in_array($lang, $acceptLang) ? $lang : 'en'; require_once "index_{$lang}.php"; ?>
HUX布斯
TA贡献1876条经验 获得超6个赞
function prefered_language(array $available_languages, $http_accept_language) { $available_languages = array_flip($available_languages); $langs; preg_match_all('~([\w-]+)(?:[^,\d]+([\d.]+))?~', strtolower($http_accept_language), $matches, PREG_SET_ORDER); foreach($matches as $match) { list($a, $b) = explode('-', $match[1]) + array('', ''); $value = isset($match[2]) ? (float) $match[2] : 1.0; if(isset($available_languages[$match[1]])) { $langs[$match[1]] = $value; continue; } if(isset($available_languages[$a])) { $langs[$a] = $value - 0.1; } } arsort($langs); return $langs;}
//$_SERVER["HTTP_ACCEPT_LANGUAGE"] = 'en-us,en;q=0.8,es-cl;q=0.5,zh-cn;q=0.3'; // Languages we support$available_languages = array("en", "zh-cn", "es"); $langs = prefered_language($available_languages, $_SERVER["HTTP_ACCEPT_LANGUAGE"]);/* Result Array ( [en] => 0.8 [es] => 0.4 [zh-cn] => 0.3 )*/
- 3 回答
- 0 关注
- 783 浏览
添加回答
举报
0/150
提交
取消