当前位置: 移动技术网 > IT编程>开发语言>PHP > 利用谷歌 Translate API制作自己的翻译脚本

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

2019年03月24日  | 移动技术网IT编程  | 我要评论

php代码:

复制代码 代码如下:

#!/usr/bin/php -q
<?php
/**
 * php script for google translate
 * @author:yishan wang
 * @version:1.0.0
 */
class google_api_translator
{
 public $url = "http://translate.google.com/translate_t";
 public $text = "";
 public $out = "";
 public $ip = '';
 function settext($text){
  $this->text = $text;
 }
 function translate($from='auto',$to='zh-cn'){
  $this->out = "";
  $gphtml = $this->postpage($this->url, $this->text,$from,$to);
  preg_match_all('/<span/s+title/="[^>]+>([^<]+)<//span>/i',$gphtml,$res);
  $this->out = $res[1][0];
  return $this->out;
 }
 /*
 $from  需要翻译的语言
 $to    翻译的语言
 */
 function postpage($url, $text,$from='auto',$to='zh-cn'){
  $html ='';
  if($url != "" && $text != "") {
   $ch = curl_init($url);
   curl_setopt($ch, curlopt_returntransfer, 1);
   if(!empty($this->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 中国 ,汉译英

>>>

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网