我创建了一个多语言网站,我想知道如何获得语言数据。嗯,我的代码从浏览器获取有关用户语言的信息,然后包含区域设置文件。
获取用户语言:
<?php
$hl = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
?>包括区域设置:
<?php
if (file_exists('locales/".$hl.".php')){
include "locales/".$hl.".php";
}else{
include "locales/en.php";
}
/* VS */
switch ($hl){
case 'de': include "locales/de.php"; break;
case 'fr': include "locales/fr.php"; break;
/* ...*/
default: include "locales/en.php";
}
?>哪种方式最好?
发布于 2018-05-09 02:28:27
有很多方法可以解决这个问题,这取决于我们在代码中不知道的许多事情。例如,locales/en.php是否始终可用(即不需要file_exists()检查)。等等等等
即使到那时,什么是最好的,也可以说是个人意见。
就我个人而言,为了干净、简单但又不过分,我更喜欢:
$hl = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
file_exists('locales/'.$hl.'.php')
? include 'locales/'.$hl.'.php'
: include 'locales/en.php';但这仍然取决于你,以及什么对你的需求和其他编码风格有意义。例如,如果重用确定语言的值(例如"EN“或来自服务器变量的值(例如"DE")会很有用),那么这样会更好:
$hl = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$language = file_exists('locales/'.$hl.'.php')
? $h1
: 'en';
include 'locales/'.$language.'.php';
// $language can be used again, eg echo "currently viewing in {$language}";你可以进一步收紧它,但要小心不要让它变得不清楚。
$browserLanguageFile = 'locales/'.substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2).'.php';
file_exists($browserLanguageFile)
? include $browserLanguageFile
: include 'locales/en.php';https://stackoverflow.com/questions/50239655
复制相似问题