Home  >  Article  >  Backend Development  >  让你的网站首页自动选择语言转跳_php技巧

让你的网站首页自动选择语言转跳_php技巧

WBOY
WBOYOriginal
2016-05-17 09:43:02897browse

大家都在用google,你用中文系统打开google的首页,打开的自然是中文首页,而不会是其他语言。因为google会自动判断用户系统使用的首选语言是什么。 
怎样才能做到像google那样呢,其实很简单, 
在浏览器发给web服务器的 HTTP Headers Information 中包含了这样一个信息 Accept-Language 
这个信息就是,浏览器中 工具->Internet选项->常规 下的 语言, 它就是用来设置浏览器可接受的语言首选项的, 它可以是多种可接受语言的优先排序列。 

下面以PHP为例, 
用户可接受的语言信息,放在$_SERVER['HTTP_ACCEPT_LANGUAGE']里, 
变量信息是类似这样的 "zh-cn", 如果是多语言列,是类似 "zh-cn,en;q=0.8,ko;q=0.5,zh-tw;q=0.3" 
下面的问题可以迎刃而解了。 


程序代码 


error_reporting(E_ALL ^ E_NOTICE); 

// 分析 HTTP_ACCEPT_LANGUAGE 的属性 
// 这里只取第一语言设置 (其他可根据需要增强功能,这里只做简单的方法演示) 

preg_match('/^([a-z-]+)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches); 
$lang = $matches[1]; 

switch ($lang) { 
case 'zh-cn' : 
header('Location: http://cn.example.com/');  
break; 
case 'zh-tw' : 
header('Location: http://tw.example.com/');  
break; 
case 'ko' : 
header('Location: http://ko.example.com/');  
break; 
default:  
header('Location: http://en.example.com/');  
break; 


?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn