网站自适应全球语言

实现的效果:

网站自适应全球语言

代码:

一、php,获取客户端的语言设置,如果没有$_COOKIE和$_GET['lang']就通过$_SERVER['HTTP_ACCEPT_LANGUAGE'])自动适应。

if(isset($_GET['lang']) and in_array($_GET['lang'], array('zh','cht','en','ja','ko','es','ru','ar','fr','hi','pt','de'))){

define('NOW_LANG',$_GET['lang']);

setcookie('lang', $_GET['lang'], NOW_TIME + 3153600,'/',domain);

} else{

if(isset($_COOKIE['lang']) and in_array($_COOKIE['lang'], array('zh','cht','en','ja','ko','es','ru','ar','fr','hi','pt','de'))){

define('NOW_LANG',$_COOKIE['lang']);

}else{

if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) and preg_match('/^([a-z-]+)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches)){

$lang = strtolower($matches[1]);

switch ($lang) {

case 'zh-hk':

case 'zh-mo':

case 'zh-sg':

case 'zh-tw':

case 'zh-cht':

define('NOW_LANG','cht');

setcookie('lang', 'cht', NOW_TIME + 3153600,'/',domain);

break;

case 'en':

define('NOW_LANG','en');

setcookie('lang', 'en', NOW_TIME + 3153600,'/',domain);

break;

case 'jp':

define('NOW_LANG','en');

setcookie('lang', 'en', NOW_TIME + 3153600,'/',domain);

break;

default:

define('NOW_LANG','zh');

setcookie('lang', 'zh', NOW_TIME + 3153600,'/',domain);

break;

}}else{

define('NOW_LANG','zh');

}}}

二、自动翻译代码。

function fy_true($query,$from='zh',$to=NOW_LANG)
{
global $mk;static $ossClient='';$query=trim($query);
if($from==$to or $query==''){return $query;}
$md5=md5($from.'_'.$to.'_'.$query);$sha1=sha1($from.'_'.$to.'_'.$query);
if(!$ossClient){$ossClient=require INDEX_PATH.'oss/samples/Common.php';}
$doesExist=$ossClient->doesObjectExist('huaren-hk','fy/'.substr($md5,0,3).'/'.$sha1);
if($doesExist){return $ossClient->getObject('huaren-hk','fy/'.substr($md5,0,3).'/'.$sha1);
}
if(($from=='zh' and $to=='cht')or($to=='zh' and $from=='cht')){$query2=$GLOBALS['mk']->convert($query,$to);}
else{$query2=trim(translate2($query,$to));}
if($query2){$ossClient->putObject('huaren-hk','fy/'.substr($md5,0,3).'/'.$sha1,$query2);
return $query2;}
return $query;}

简繁体采用$GLOBALS['mk']->convert 

其它的采用translate2 调用googleAPI 

缓存采用阿里云oss!$ossClient->doesObjectExist 

三、模版{lag 历史上的今天} 

实现:先对模版根据不同的语言进行编译,缓存后进行显示。这样的会翻译只要请求一次就够了!

评论

目前评论:0   

点击加载更多评