21,886
社区成员
发帖
与我相关
我的任务
分享
$query = "hello";
$from = "en";
$to = "zh-CN";
$url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=$query&langpair=$from|$to";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
echo $content;
<?php
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, "<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) {
$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|ko', 'ie=UTF-8','text='.urlencode(mb_convert_encoding($text, 'UTF-8', 'euc-kr')));
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;
}
}
//just for test
$g = new Google_API_translator();
$g->setText("사랑해");
$g->translate();
echo $g->out;
?>