• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

利用谷歌 Translate API制作自己的翻译脚本_php实例

php 搞代码 4年前 (2022-01-26) 44次浏览 已收录 0个评论

PHP代码:

#!/usr/bin/php -q<BR><?php<BR>/** <BR> * PHP Script For Google Translate<BR> * @author:Yishan Wang<BR> * @version:1.0.0<BR> */<BR>class Google_API_translator<BR>{<BR> public $url = "http://translate.google.com/translate_t";<BR> public $text = "";<BR> public $out = "";<BR> public $ip = '';<BR> function setText($text){<BR>  $this->text = $text;<BR> }<BR> function translate($from='auto',$to='zh-CN'){<BR>  $this->out = "";<BR>  $gphtml = $this->postPage($this->url, $this->text,$from,$to);<BR>  preg_match_all('/<span>]+>([^<]+)/i',$gphtml,$res);<BR>  $this->out = $res[1][0];<BR>  return $this->out;<BR> }<BR> /*<BR> $from  需要翻译的语言<BR> $to    翻译的语言<BR> */<BR> function postPage($url, $text,$from='auto',$to='zh-CN'){<BR>  $html ='';<BR>  if($url != "" && $text != "") {<BR>   $ch = curl_init($url);<BR>   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);<BR>   if(!empty($this-><i>1本文来#源gaodai$ma#com搞$代*码*网</i><pre>搞代gaodaima码

ip) && is_string($this->ip)){
curl_setopt($ch, CURLOPT_INTERFACE,$this->ip);
}
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
/*
*hl – 界面语言,此处无用。
*langpair – src lang to dest lang
*ie – urlencode的编码方式?
*text – 要翻译的文本
*/
$fields = array(‘hl=zh-CN’, ‘langpair=’.$from.’|’.$to, ‘ie=UTF-8′,’text=’.$text);
$fields = implode(‘&’, $fields);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
$html = curl_exec($ch);
if(curl_errno($ch)) $html = “”;
curl_close ($ch);
}
return $html;
}
}
$from = !empty($_REQUEST[‘fromlan’])?$_REQUEST[‘fromlan’]:’en’;
$to = !empty($_REQUEST[‘tolan’])?$_REQUEST[‘tolan’]:’zh-CN’;
$keywords = “”;
for($i=1;$i<$argc;$i++){
$keywords .= $argv[$i].” “;
}
$article = !empty($_REQUEST[‘article’])?$_REQUEST[‘article’]:$keywords;
$g = new Google_API_translator();
if(isset($_REQUEST[‘ip’]) && !empty($_REQUEST[‘ip’]))
{
$g -> ip = $_REQUEST[‘ip’];
}
$article = iconv(‘GBK’,’UTF-8′,$article);
$article = str_replace(‘{enter}’,”/r/n”,$article);
$g->setText($article);
$g->translate($from,$to);
echo “———–翻译结果————–/n”;
echo iconv(‘GBK’,’UTF-8′,$g->out);
echo “/n”;
?>

2、将以上内容保存名为“gtranslate”的文件中。

3、给gtranslate添加执行权限

chmod a+x gtranslate

4、创建软连接

ln -s /yourpath/gtranslate /usr/bin/gtranslate

5、输入测试词汇:

gtranslate Hello World


———–翻译结果————–
世界您好

>>>

6、做了个中英文互译的版本。

用 gtranslate China ,英译汉

用 gtranslate -r 中国 ,汉译英

>>>


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:利用谷歌 Translate API制作自己的翻译脚本_php实例
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址