1

我想让我的网站多语言。我如何通过首先检测浏览器的语言来简单地包含正确的语言文件,然后如果用户单击每个页面上存在的语言标志,则通过设置 cookie 来简单地包含正确的语言文件。

我找到了这个脚本:

<script>

/*
Browser Language Redirect script- By JavaScript Kit
For this and over 400+ free scripts, visit http://www.javascriptkit.com
This notice must stay intact
*/

//Enter ISO 639-2 letter Language codes to detect (see: http://www.w3.org/WAI/ER/IG/ert/iso639.htm):
var langcodes=new Array("en", "de", "it", "default")

//Enter corresponding redirect URLs (last one is for default URL):
var langredirects=new Array("english/index.php", "deutsch/index.php", "italiano/index.php", "english/index.php")

var languageinfo=navigator.language? navigator.language : navigator.userLanguage
var gotodefault=1

function redirectpage(dest){
if (window.location.replace)
window.location.replace(dest)
else
window.location=dest
}

for (i=0;i<langcodes.length-1;i++){
if (languageinfo.substr(0,2)==langcodes[i]){
redirectpage(langredirects[i])
gotodefault=0
break
}
}

if (gotodefault)
redirectpage(langredirects[langcodes.length-1])


</script>
4

1 回答 1

0

看看这是否能得到你想要的:

if (!isset($_SESSION['locale'])){
    // See if the client headers tell us what language they want. If not, 
    // default to U.S. English.
    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
        $lang = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
        $pattern = '/^(?P<primarytag>[a-zA-Z]{2,8})'.'(?:-(?P<subtag>[a-zA-Z]{2,8}))?(?:(?:;q=)'.'(?P<quantifier>\d\.\d))?$/';
        $splits = array();

        if (preg_match($pattern, $lang[0], $splits)) {
            if (isset($splits[1]) && isset($splits[2])){
                $_SESSION['locale'] = "$splits[1]_$splits[2]";
            }else{
                $_SESSION['locale'] = 'en_US';
            }
        } else {
            $_SESSION['locale'] = 'en_US';
        }
    }else{
        $_SESSION['locale'] = 'en_US';
    }
}
于 2012-12-20T21:55:58.830 回答