首頁  >  文章  >  後端開發  >  百度翻译 接口使用实例

百度翻译 接口使用实例

WBOY
WBOY原創
2016-07-23 08:54:471659瀏覽
百度翻译接口类
  1. /**
  2. * 百度开发者中心:http://developer.baidu.com/
  3. * 百度翻译API:http://developer.baidu.com/wiki/index.php?title=docs
  4. */
  5. class baiduAPI{
  6. /**
  7. * $from : 源语言语种:语言
  8. * $to : 目标语言语种:语言代码或auto
  9. */
  10. static public function fanyi($value, $from="auto", $to="auto")
  11. {
  12. $value_code=urlencode($value);
  13. #首先对要翻译的文字进行 urlencode 处理
  14. $appid="Ow83extUdl2zLm94s7ldkw5D";
  15. #您注册的API Key
  16. $languageurl = "http://openapi.baidu.com/public/2.0/bmt/translate?client_id=" . $appid ."&q=" .$value_code. "&from=".$from."&to=".$to;
  17. #生成翻译API的URL GET地址
  18. $text=json_decode(self::language_text($languageurl));
  19. $text = isset($text->trans_result) ? $text->trans_result : '';
  20. return isset($text[0]->dst) ? $text[0]->dst : '';
  21. }
  22. #获取目标URL所打印的内容
  23. static function language_text($url)
  24. {
  25. if(!function_exists('file_get_contents')) {
  26. $file_contents = file_get_contents($url);
  27. } else {
  28. $ch = curl_init();
  29. $timeout = 5;
  30. curl_setopt ($ch, CURLOPT_URL, $url);
  31. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  32. curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  33. $file_contents = curl_exec($ch);
  34. curl_close($ch);
  35. }
  36. return $file_contents;
  37. }
  38. }
复制代码
实例1,(中文翻译英文)
  1. # 定义需要翻译的内容
  2. $title = '你好';
  3. # 验证是否为汉字 ( 兼容gb2312,utf-8 )
  4. if (preg_match("/[\x7f-\xff]/", $title)) {
  5. $title = baiduAPI::fanyi($title, $from="zh", $to="en");
  6. } else {
  7. $title = baiduAPI::fanyi($title, $from="en", $to="zh");
  8. $title = iconv('utf-8', 'gbk', $title);
  9. }
  10. # 结果输出 Hello
  11. echo $title;
  12. exit;
复制代码
实例2,(英文翻译中文)
  1. # 定义需要翻译的内容
  2. $title = 'Hello';
  3. # 验证是否为汉字 ( 兼容gb2312,utf-8 )
  4. if (preg_match("/[\x7f-\xff]/", $title)) {
  5. $title = baiduAPI::fanyi($title, $from="zh", $to="en");
  6. } else {
  7. $title = baiduAPI::fanyi($title, $from="en", $to="zh");
  8. $title = iconv('utf-8', 'gbk', $title);
  9. }
  10. # 结果输出 您好
  11. echo $title;
  12. exit;
复制代码


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn