PHP Google的translate API代码

yipeiwu_com5年前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的就这里,参见了部分同学的部分代码。具体忘了。
这段代码不好。。。但可以用,懒得管啦。。

相关文章

php 获取SWF动画截图示例代码

1.下载附件,并安装,方法看附件中的帮助 2.拷贝代码进合适位置,生成图片,怎么处理,自己看着办喽 复制代码 代码如下: $oldswf = "/uploads/swf/test.swf...

使用ETags减少Web应用带宽和负载第1/2页

介绍 最近,大众对于REST风格应用架构表现出强烈兴趣,这表明Web的优雅设计开始受到人们的注意。现在,我们逐渐理解了“3W架构(Architecture of the World W...

php gd2 上传图片/文字水印/图片水印/等比例缩略图/实现代码

复制代码 代码如下:<?php //上传文件类型列表 $uptypes=array( 'image/jpg', 'image/jpeg', 'image/png', 'image/...

php中magic_quotes_gpc对unserialize的影响分析

本文实例分析了php中magic_quotes_gpc对unserialize的影响。分享给大家供大家参考。具体如下: magic_quotes_gpc是一个php中一个给单双引号增加一...

关于php支持分块与断点续传文件下载功能代码

本文章要介绍了这篇文章是一篇关于php流下载,就是可以支持分块与断点续传文件下载,有需要的朋友可以看看。代码如下 复制代码 代码如下: $dowmFile = dirname ( __F...