Heim  >  Artikel  >  Backend-Entwicklung  >  百度翻译 接口使用实例

百度翻译 接口使用实例

WBOY
WBOYOriginal
2016-07-23 08:54:471660Durchsuche
百度翻译接口类
  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;
复制代码


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn