找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1318|回复: 0

[教程] Google翻译接口(PHP API)

[复制链接]
发表于 2013-4-12 09:18:27 | 显示全部楼层 |阅读模式 来自 广东省湛江市
  1. /* Google翻译PHP接口
  2.   * 官成文 2009-03-28
  3.   * http://blog.csdn.net/aprin/
  4.   * 注意:如果翻译文本为UTF-8编码,则要删去mb_convert_encoding函数
  5.   */
  6. class Google_API_translator {
  7.   public $url = "http://translate.google.com/translate_t";
  8. public $text = "";//翻译文本
  9. public $out = ""; //翻译输出
  10. function setText($text){
  11.   $this->text = $text;
  12.   }
  13. function translate() {
  14.   $this->out = "";
  15. $gphtml = $this->postPage($this->url, $this->text);
  16. //提取翻译结果
  17. $out = substr($gphtml, strpos($gphtml, "
  18. "));
  19. $out = substr($out, 29);
  20.   $out = substr($out, 0, strpos($out, "
  21. ));
  22. $this->out = $out;
  23.   return $this->out;
  24.   }
  25. function postPage($url, $text) {
  26.   $html =";
  27. if($url != "" && $text != "") {
  28.   $ch = curl_init($url);
  29.   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  30.   curl_setopt($ch, CURLOPT_HEADER, 1);
  31.   curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  32.   curl_setopt($ch, CURLOPT_TIMEOUT, 15);
  33. /*
  34.   *hl – 界面语言,此处无用。
  35. *langpair – src lang to dest lang
  36.   *ie – urlencode的编码方式?
  37.   *text – 要翻译的文本
  38. */
  39.   $fields = array('hl=zh-CN', 'langpair=zh-CN|en', 'ie=UTF-8′,'text='.urlencode(mb_convert_encoding($text, 'UTF-8′, 'GB2312′)));
  40.   curl_setopt($ch, CURLOPT_POST, 1);
  41.   curl_setopt($ch, CURLOPT_POSTFIELDS, implode('&', $fields));
  42. $html = curl_exec($ch);
  43. if(curl_errno($ch)) $html = "";
  44. curl_close ($ch);
  45.   }
  46.   return $html;
  47.   }
  48.   }
  49. //just for test
  50.   $g = new Google_API_translator();
  51.   $g->setText("我爱php100!");
  52.   $g->translate();
  53.   echo $g->out;
  54. ?>
复制代码

发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;

如何回报帮助你解决问题的坛友,好办法就是点击帖子下方的评分按钮给对方加【金币】不会扣除自己的积分,做一个热心并受欢迎的人!

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则 需要先绑定手机号

关闭

站长推荐上一条 /1 下一条

QQ|侵权投诉|广告报价|手机版|小黑屋|西部数码代理|飘仙建站论坛 ( 豫ICP备2022021143号-1 )

GMT+8, 2024-5-2 10:05 , Processed in 0.036565 second(s), 11 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表