<?php /* Google翻译PHP接口 */ class Google_API_translator { public $url = "http://translate.google.com/translate_t"; public $text = "";//翻译文本 public $out = ""; //翻译输出 public $lang_src = "";//要翻译的语言 public $lang_des = "";//翻译成的语言 function setText($text){ $this->text = $text; } function setLang($lang_src,$lang_des){ $this->lang_src = $lang_src; $this->lang_des = $lang_des; } function translate() { $this->out = ""; $gphtml = $this->postPage($this->url, $this->text,$this->lang_src,$this->lang_des); $out = substr($gphtml, strpos($gphtml, "<div id=result_box dir=\"ltr\">")); $out = substr($out, 29); $out = substr($out, 0, strpos($out, "</div>")); $this->out = $out; return $this->out; } function postPage($url, $text,$lang_src,$lang_des) { $html =''; if($url != "" && $text != ""&&$lang_src != ""&&$lang_des != "") { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 15); /* *hl - 界面语言 此处无用。 *langpair - src lang to dest lang *ie - urlencode的编码方式? *text - 要翻译的文本 */ $fields = array('hl=zh-CN', 'langpair='.$lang_src.'|'.$lang_des, 'ie=UTF-8','text='.urlencode(mb_convert_encoding($text, 'UTF-8', 'GB2312'))); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, implode('&', $fields)); $html = curl_exec($ch); if(curl_errno($ch)) $html = ""; curl_close ($ch); } return $html; } } ?>