程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> PHP Google的translate API代碼

PHP Google的translate API代碼

編輯:關於PHP編程

新建一個ANSI的PHP文件,然後創建一個類:
復制代碼 代碼如下:
header("Content-Type: text/html; charset=utf-8");
class Google_API_translator{
public $opts = array("text" => "", "language_pair" => "en|it");
public $out = "";
function setOpts($opts) {
if($opts["text"] != "") $this->opts["text"] = $opts["text"];
if($opts["language_pair"] != "") $this->opts["language_pair"] = $opts["language_pair"];
}
function translate() {
$this->out = "";
$google_translator_url = "http://translate.google.com/translate_t?langpair=".urlencode($this->opts["language_pair"])."&;";
$google_translator_data .= "text=".urlencode($this->opts["text"]);
$gphtml = $this->postPage(array("url" => $google_translator_url, "data" => $google_translator_data));
$out = substr($gphtml, strpos($gphtml, "
"));
$out = substr($out, 29);
$out = substr($out, 0, strpos($out, "
"));
$this->out = utf8_encode($out);
return $this->out;
}
function postPage($opts) {
$html ='';
if($opts["url"] != "" && $opts["data"] != "") {
$ch = curl_init($opts["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);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $opts["data"]);
$html = curl_exec($ch);
if(curl_errno($ch)) $html = "";
curl_close ($ch);
}
return $html;
}
}
?>

使用的時候
復制代碼 代碼如下:
$g = new Google_API_translator();
$g->setOpts(array("text" => "Cjjer是天才", "language_pair" => "zh-CN|en"));
$g->translate();
echo $g->out;
?>

這樣就可以了,輸出:Cjjer is genius
PHP的就這裡,參見了部分同學的部分代碼。具體忘了。
這段代碼不好。。。但可以用,懶得管啦。。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved