您好,欢迎访问一九零五行业门户网

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

php代码:
复制代码 代码如下:
#!/usr/bin/php -q
text = $text;
 }
 function translate($from='auto',$to='zh-cn'){
  $this->out = ;
  $gphtml = $this->postpage($this->url, $this->text,$from,$to);
  preg_match_all('/]+>([^/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  $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 中国 ,汉译英
>>>
http://www.bkjia.com/phpjc/779569.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/779569.htmltecharticlephp代码: 复制代码 代码如下: #!/usr/bin/php -q ?php /** * php script for google translate * @author:yishan wang * @version:1.0.0 */ class google_api_translator { public...
其它类似信息

推荐信息