- // ----------------------------------------------------------------------
- // | php mvc framework v1.0 在线翻译类 使用百度翻译接口 无需申请api key
- // ----------------------------------------------------------------------
- // | 凯发网娱乐官网 copyright (c) 2014-2099 http://qiling.org all rights reserved.
- // ----------------------------------------------------------------------
- // | licensed ( http://www.apache.org/licenses/license-2.0 )
- // ----------------------------------------------------------------------
- // | author: qiling <[email protected]> 2015年4月13日 下午2:22:15
- // ----------------------------------------------------------------------
- /**
- * 在线翻译类
- * @author qiling <[email protected]>
- */
- class translate {
- /**
- * 支持的语种
- * @var arrayaccess
- */
- static $lang = array (
- 'auto' => '自动检测',
- 'ara' => '阿拉伯语',
- 'de' => '德语',
- 'ru' => '俄语',
- 'fra' => '法语',
- 'kor' => '韩语',
- 'nl' => '荷兰语',
- 'pt' => '葡萄牙语',
- 'jp' => '日语',
- 'th' => '泰语',
- 'wyw' => '文言文',
- 'spa' => '西班牙语',
- 'el' => '希腊语',
- 'it' => '意大利语',
- 'en' => '英语',
- 'yue' => '粤语',
- 'zh' => '中文'
- );
- /**
- * 获取支持的语种
- * @return array 返回支持的语种
- */
- static function getlang() {
- return self::$lang;
- }
- /**
- * 执行文本翻译
- * @param string $text 要翻译的文本
- * @param string $from 原语言语种 默认:中文
- * @param string $to 目标语种 默认:英文
- * @return boolean string 翻译失败:false 翻译成功:翻译结果
- */
- static function exec($text, $from = 'zh', $to = 'en') {
- // http://fanyi.baidu.com/v2transapi?from=zh&query=用车资讯&to=fra
- $url = "http://fanyi.baidu.com/v2transapi";
- $data = array (
- 'from' => $from,
- 'to' => $to,
- 'query' => $text
- );
- $data = http_build_query ( $data );
- $ch = curl_init ();
- curl_setopt ( $ch, curlopt_url, $url );
- curl_setopt ( $ch, curlopt_referer, "http://fanyi.baidu.com" );
- curl_setopt ( $ch, curlopt_useragent, 'mozilla/5.0 (windows nt 6.1; rv:37.0) gecko/20100101 firefox/37.0' );
- curl_setopt ( $ch, curlopt_header, 0 );
- curl_setopt ( $ch, curlopt_post, 1 );
- curl_setopt ( $ch, curlopt_postfields, $data );
- curl_setopt ( $ch, curlopt_returntransfer, 1 );
- curl_setopt ( $ch, curlopt_timeout, 10 );
- $result = curl_exec ( $ch );
- curl_close ( $ch );
- $result = json_decode ( $result, true );
- if (!isset($result ['trans_result'] ['data'] ['0'] ['dst'])){
- return false;
- }
- return $result ['trans_result'] ['data'] ['0'] ['dst'];
- }
- }
- // 使用示例:
- echo translate::exec ( "你好,世界!" );