中山php|最优网络中山做网站 中山php建站

最优良人

2012/07/14 at 15:41

php利用谷歌实现自动在线翻译

php利用谷歌实现自动翻译,以下是两种实现的方式,php文档用utf8就不会出现乱码问题

第一种利用curl:

function translate($text,$language='zh-cn|en'){
if(empty($text))return false;
@set_time_limit(0);
$html = "";
$ch=curl_init("http://google.com/translate_t?langpair=".urlencode($language)."&text=".urlencode($text));
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
$html=curl_exec($ch);
if(curl_errno($ch))$html = "";
curl_close($ch);
if(!empty($html)){
$x=explode("</span></span></div></div>",$html);
$x=explode("onmouseout=\"this.style.backgroundColor='#fff'\">",$x[0]);
return $x[1];
}else{
return false;
}
}
echo translate('去');
第二种:利用get方式
function googleTran($text){
if(empty($text)) return "";
//反间碟
$wf=@file_get_contents('http://translate.google.cn/translate_t?sl=zh-CN&tl=en&text='.$text.'#');
if (false===$wf||empty($wf)){
return false;
}

//截取相关信息
$return = "";

$star="style.backgroundColor='\#fff'\">";

$end="</span></span></div>";
$p = "#{$star}(.*){$end}#iU";//i表示忽略大小写,U禁止贪婪匹配
if(preg_match_all($p,$wf,$rs))
{ print_r($rs);
return $rs[1][0];}

}

echo googleTran('去');

-