i漂泊

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 7672|回复: 1

Google翻译接口(PHP API)

[复制链接]
TA的礼物信息
  • 收到:0
  • 送出:2
发表于 2013-7-16 19:30:52 | 显示全部楼层 |阅读模式
  1. /* Google翻译PHP接口
  2. * 注意:如果翻译文本为UTF-8编码,则要删去mb_convert_encoding函数
  3. */

  4. class Google_API_translator {
  5. public $url = “http://translate.google.com/translate_t”;
  6. public $text = “”;//翻译文本
  7. public $out = “”; //翻译输出

  8. function setText($text){
  9. $this->text = $text;
  10. }

  11. function translate() {
  12. $this->out = “”;

  13. $gphtml = $this->postPage($this->url, $this->text);

  14. //提取翻译结果
  15. $out = substr($gphtml, strpos($gphtml, “

  16. “));
  17. $out = substr($out, 29);
  18. $out = substr($out, 0, strpos($out, “

  19. “));

  20. $this->out = $out;
  21. return $this->out;
  22. }

  23. function postPage($url, $text) {
  24. $html =”;

  25. if($url != “” && $text != “”) {
  26. $ch = curl_init($url);
  27. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  28. curl_setopt($ch, CURLOPT_HEADER, 1);
  29. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  30. curl_setopt($ch, CURLOPT_TIMEOUT, 15);

  31. /*
  32. *hl – 界面语言,此处无用。
  33. *langpair – src lang to dest lang
  34. *ie – urlencode的编码方式?
  35. *text – 要翻译的文本
  36. */
  37. $fields = array(‘hl=zh-CN’, ‘langpair=zh-CN|en’, ‘ie=UTF-8′,’text=’.urlencode(mb_convert_encoding($text, ‘UTF-8′, ‘GB2312′)));
  38. curl_setopt($ch, CURLOPT_POST, 1);
  39. curl_setopt($ch, CURLOPT_POSTFIELDS, implode(‘&’, $fields));

  40. $html = curl_exec($ch);
  41. if(curl_errno($ch)) $html = “”;
  42. curl_close ($ch);
  43. }
  44. return $html;
  45. }
  46. }

  47. //just for test
  48. $g = new Google_API_translator();
  49. $g->setText(“我爱Java!”);
  50. $g->translate();
  51. echo $g->out;
  52. ?>
复制代码
回复

使用道具 举报

TA的礼物信息
  • 收到:0
  • 送出:0
发表于 2013-8-5 11:52:07 | 显示全部楼层
楼主发的是好帖、支持下、
回复 支持 反对

使用道具 举报

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

本版积分规则

QQ|小黑屋|手机版|IPiaoBo Inc. ( 渝ICP备17002826号 )

GMT+8, 2025-5-6 23:17 , Processed in 0.079467 second(s), 50 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

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