我想用HTTP_ACCEPT_LANGUAGE函数写一个简单的if语句,根据用户浏览器语言的结果进行重定向。这是我目前所掌握的,但"如果"的说法还需要改进。有人能帮我修一下吗?
<?php
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
if ($lang=german) {
header("Location: http://www.example.com/german/index.html");
} else if ($lang=spanish) {
header("Location: http://www.example.com/spanish/index.html");
}
else if ($lang=french) {
header("Location: http://www.example.com/french/index.html");
}
else if ($lang=chinese) {
header("Location: http://www.example.com/chinese /index.html");
} else {
echo "<html>english content</html>";
}
?>
我不知道你的语言文字是什么,所以我想让它们成为ISO语言代码。
使用switch
语句,这更可读、更小:
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
switch($lang) {
case "de-DE":
case "es-ES":
case "cn-CN":
case "fr-FR":
header("Location: http://www.example.com/$lang/index.html");
break;
default:
header("Location: http://www.example.com/en-US/index.html");
break;
}
此外,你是在分配,而不是比较。与==
:进行比较
if ($lang == "de-DE")
假设你总是重定向到/language/,你可以这样做:
<?php
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
if ( in_array( $lang,array("german","spanish","french","chinese") ) ) {
header("Location: http://www.example.com/$lang/index.html");
} else {
echo "<html>english content</html>";
}
?>
此外,if
中的比较需要与==
进行,否则就是任务!
试试这个:
<?php
$path = array(
'en-US' => 'english',
// etc
);
$accepts = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
if (in_array($accepts[0], $path)) { // if path exists for language then redirect to path, else redirect to default path (english)
header('Location: http://www.example.com/' . $path[$accepts[0]] . '/index.html');
} else {
header('Location: http://www.example.com/english/index.html');
}
?>
HTTP_ACCEPT_LANGUAGE返回的不是"english",而是像"en"这样的两个符号符号,或者像"en_us"这样的区域和语言符号。你不应该使用if语句,因为它很难阅读。您应该使用数组(将来您可以简单地将其写入配置文件,或者移动到数据库)。正确的代码应该是这样的:
$default_lang = 'en';
$lang_redirectors = array('de' => 'http://www.example.com/german/index.html',
'en' => 'http://www.example.com/english/index.html');
function redirect($url){
header("Location: " . $url);
}
$hal = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$langs = explode($hal, ',');
foreach($langs as $lang){
$lang_prefix = substr($lang, 0, 2);
if(in_array($lang_prefix, $lang_redirectors)){
redirect($lang_redirectors[$lang_prefix]);
break;
}
redirect($lang_redirectors[$default_lang]);
}
<?php
$browserlang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$lang = $browserlang[0] . $browserlang[1] . $browserlang[2] . $browserlang[3] . $browserlang[4];
if (($lang=="sk_SK") OR ($lang=="sk-SK")) {
header("Location: https://www.example.sk/sk");
}
else if (($lang=="en_EN") OR ($lang=="en-EN") OR ($lang=="en_GB") OR ($lang=="en_US") OR ($lang=="en-GB") OR ($lang=="en-US")) {
header("Location: https://www.example.sk/en");
}
else {
header("Location: https://www.example.sk/en");
}
?>
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
switch($lang) {
case "ru":
header("Location: https://example.com/ru");
break;
case "ka":
header("Location: https://example.com/ka");
break;
default:
header("Location: https://example.com/en");
break;