Google翻译PHP接口

2010-08-27   来源:站长日记       编辑:沧海桑田   类别:PHP 教程    转载到:    发表评论

* 注意:如果翻译文本为UTF-8编码,则要删去 mb_convert_encoding 函数
$g = new Google_API_translator();
$g->setText("我爱Java!");
$g->translate();
echo $g->out;
思路,不一定可用
class Google_API_translator {
public $url = "http://translate.google.com/translate_t";
public $text = "";//翻译文本
public $out = ""; //翻译输出

function setText($text){
  $this->text = $text;
}

function translate() {
  $this->out = "";
  $gphtml = $this->postPage($this->url, $this->text);
  //提取翻译结果
  $out = substr($gphtml, strpos($gphtml, " "));
  $out = substr($out, 29);
  $out = substr($out, 0, strpos($out, ""));
  $this->out = $out;
  return $this->out;
}

function postPage($url, $text) {
   $html ='';

  if($url != "" && $text != "") {
   $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);

  
   $fields = array('hl=zh-CN', 'langpair=zh-CN|en', 'ie=UTF-8','text='.urlencode($text)
   //'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;
  }
}

0

0
0|0 | 鲜花 VS 砸蛋 | 51阅读 0评论
 
不想登录?直接点击发布即可作为游客留言。
昵称  邮箱 网站 验证码 = 1+1