PHP版Google翻译api

后端开发PHP 891

调用的api地址是:

http://translate.google.cn/translate_a/single?client=gtx&dt=t&ie=UTF-8&oe=UTF-8&sl=auto&tl=en&q=

这里的tlq参数分别对应是目标语言要翻译的内容

public static function translate($word, $en = 'en')
    {
        if( empty($word) ) return '';
        $word = htmlspecialchars($word, ENT_NOQUOTES);
        $len = mb_strlen($word, 'UTF-8');
        $l = 5000; #单次最大翻译内容长度
            $url = 'http://translate.google.cn/translate_a/single?client=gtx&dt=t&ie=UTF-8&oe=UTF-8&sl=auto&tl='.$en.'&q=';
        $text = '';
        for($i = 0; $i < $len; $i += $l)
        {
            $fanyi = self::curl(['url'=>$url.urlencode( mb_substr( $word, $i, $l, "UTF-8" ) ),'header'=>self::headerInfo(),'cookie'=>'']);
            if(!empty($fanyi['content']))
            {
                $json = json_decode($fanyi['content'], true);
                if(isset($json[0][0][0]) && !empty($json[0][0][0]))$text .= $json[0][0][0];
            }
        }
        return $text;
    }

Post Comment