语言重定向不起作用


Language redirect not working

我正在努力处理基于语言检测将用户重定向到其他页面的代码。我发现这个代码看起来很有希望,因为到目前为止,我还没有从这个网站上的其他帖子中得到任何运气。我唯一的问题与第一行代码有关。我在第一行的"部分放了什么?

<?php
$lc = ""; // Initialize the language code variable
// Check to see that the global language server variable isset()
// If it is set, we cut the first two characters from that string
    if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
    $lc = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
}
// Now we simply evaluate that variable to detect specific languages
if($lc == "fr"){
    header("location: index_french.php");
    exit();
} else if($lc == "de"){
    header("location: index_german.php");
    exit();
}
?>
<h2>Hello Default Language User</h2>
<h3><?php echo "Your 2-letter Code is: ".$lc; ?></h3>

当我运行此代码时,我收到一条错误消息:

警告:无法修改标头信息-标头已由第12行/home/m3418630/public_html/sumoresources/index.php中的(输出起始于/home/m32418630/public_html/sumoreresources/index.php)发送

有人能解释为什么会发生这种情况吗?

感谢

在代码片段中,必须为变量$lc设置默认语言。如果服务器从当前请求中发送语言代码,它将被覆盖。

这个片段可以从用户的浏览器中检测语言

    $locale = null;
    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {   
            $languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
            foreach ($languages as $lang) {
                $lang = str_replace('-', '_', trim($lang));
                if (false === strpos($lang, '_')) {
                        $locale = strtoupper($lang);
                } else {
                    $lang = explode('_', $lang);
                    if (count($lang) == 3) {
                        $locale = strtolower($lang[0]) . ucfirst($lang[1]) . strtoupper($lang[2]);
                    } else {
                        $locale = strtolower($lang[0]) . strtoupper($lang[1]);
                    }
                }
            }
        }
echo $locale;

参见http://codepad.viper-7.com/F1XfU5

您没有在那里放任何东西,它只是按照注释中的说明启动变量。

如果您收到一个header ready sended错误,这意味着您在发送header()之前将信息输出到页面,如果不使用ob_start()、ob_end_flush()进行缓冲,就无法做到这一点。