项目中经常遇到翻译需求,相信很多程序员也写代码的时候也是一边coding,一边Google translate。前天分享了一个星期的英汉互译功能在soul上引起了很多小盆友的讨论。所以今天波波再分享一个PHP版的谷歌翻译,希望对需要自动翻译的朋友有所帮助。
代码片段:
- <?php
- function gtranslate($text,$to='en'){
- $entext = urlencode($text);
- $url = 'https://translate.google.cn/translate_a/single?client=gtx&dt=t&ie=UTF-8&oe=UTF-8&sl=auto&tl='.$to.'&q='.$entext;
- set_time_limit(0);
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
- curl_setopt($ch, CURLOPT_HEADER, false);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
- curl_setopt($ch, CURLOPT_MAXREDIRS,20);
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 40);
- curl_setopt($ch, CURLOPT_URL, $url);
- $result = curl_exec($ch);
- curl_close($ch);
- $result = json_decode($result);
- if(!emptyempty($result)){
- foreach($result[0] as $k){
- $v[] = $k[0];
- }
- return implode(" ", $v);
- }
- }
- $longtext = "今天天气很好";
- echo gtranslate($longtext);
附:PHP版星期英汉互译function
- /*
- * Week英汉互译
- * @param $keyword string 待翻译的星期
- * @param $en2zh boole 默认英译汉
- * @return string
- */
- function week_trans($keyword,$en2zh=true){
- $weeken = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday'];
- $weekzh = ['星期一','星期二','星期三','星期四','星期五','星期六','星期天'];
- $data = "";
- if($en2zh && in_array($keyword,$weeken)){
- $data = $weekzh[array_search($keyword,$weeken)];
- }
- if(false == $en2zh && in_array($keyword,$weekzh)){
- $data = $weeken[array_search($keyword,$weekzh)];
- }
- return $data;
- }
最近波波重写了PHP的array_push函数,稍后也更新在博客置顶文章《常用PHP业务逻辑》中,敬请期待。