PHP Google的translate API代码

前端之家收集整理的这篇文章主要介绍了PHP Google的translate API代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

新建一个ANSI的PHP文件,然后创建一个类:
<div class="codetitle"><a style="CURSOR: pointer" data="10239" class="copybut" id="copybut10239" onclick="doCopy('code10239')"> 代码如下:

<div class="codebody" id="code10239">
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,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,CURLOPT_FOLLOWLOCATION,CURLOPT_TIMEOUT,15);
curl_setopt($ch,CURLOPT_POST,CURLOPT_POSTFIELDS,$opts["data"]);
$html = curl_exec($ch);
if(curl_errno($ch)) $html = "";
curl_close ($ch);
}
return $html;
}
}
?>

使用的时候
<div class="codetitle"><a style="CURSOR: pointer" data="1953" class="copybut" id="copybut1953" onclick="doCopy('code1953')"> 代码如下:
<div class="codebody" id="code1953">
$g = new Google_API_translator();
$g->setOpts(array("text" => "Cjjer是天才","language_pair" => "zh-CN|en"));
$g->translate();
echo $g->out;
?>

这样就可以了,输出:Cjjer is genius
PHP的就这里,参见了部分同学的部分代码。具体忘了。
这段代码不好。。。但可以用,懒得管啦。。

原文链接:https://www.f2er.com/php/29363.html

猜你在找的PHP相关文章