PHP調用google translate中解決中文返回亂碼

在網上找了段代碼獲取google翻譯結果,不是調用API的。

結果返回結果中中文亂碼,並且結果不正確,那麼其實發過去的時候就轉碼有問題。

返回來的就有問題。

$google = $this->curl_file_get_contents("http://translate.google.com/translate_a/t?client=t&text=".$text."&sl=zh_CN&tl=en");

原來的寫法返回的中文亂碼

解決方法:

加入

$google = $this->curl_file_get_contents("http://translate.google.com/translate_a/t?client=t&ie=UTF-8&oe=UTF-8&text=".$text."&sl=zh_CN&tl=en");
echo $google

返回結果正常

    public function curl_file_get_contents($durl){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $durl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 獲取數據返回
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在啓用 CURLOPT_RETURNTRANSFER 時候將獲取數據返回
        $r = curl_exec($ch);
        curl_close($ch);
        return $r;
    }

修改後的完整源代碼:

<?php
        
    header("Content-Type: text/html; charset=utf-8");

    class Google_API_translator {

        public $out = "";

        function translate( $content, $s, $t ) {
            
            $this->out = "";
            
            $text = urlencode( $content );//要翻譯的單詞  

            $google_translator_url = "http://translate.google.com/translate_a/t?client=t&ie=UTF-8&oe=UTF-8&text=".$text."&sl=".$s."&tl=".$t;
         
            $gphtml = $this->postPage(array("url" => $google_translator_url));

            $this->out = utf8_encode($gphtml);
            
            return $this->out;
        }
        
        function postPage($opts) {
            
            $html = "";
            
            if($opts["url"] != "") {
                
                $ch = curl_init();
                
                curl_setopt($ch, CURLOPT_URL, $opts["url"]);

                $html = curl_exec($ch);


                if(curl_errno($ch)) $html = "";
                curl_close ($ch);  
                
            }
            
            
            return $html;
        }
    }

    $g = new Google_API_translator();

    $g->translate( $_GET['q'], $_GET['s'], $_GET['t']);

?>

訪問方法:

http://eqiyu.cn/translator.php?q=%E6%B5%8B%E8%AF%95&s=zh-CN&t=ja

返回:

[[["テスト","測試","Tesuto","Cèshì"]],,"zh-CN",,[["テスト",[1],false,false,999,0,1,0]],[["測試",1,[["テスト",999,false,false],["試験",0,false,false],["検査",0,false,false],["のテスト",0,false,false],["実験",0,false,false]],[[0,2]],"測試"]],,,[["zh-CN"]],13]

http://eqiyu.cn/translator.php?q=%E6%B5%8B%E8%AF%95&s=zh-CN&t=en

返回:

[[["Test","測試","","Cèshì"]],[["noun",["test","examination"],[["test",["測試","試驗","試","實驗","考試","考驗"],[15246],0.29559943],["examination",["考試","檢查","試","研究","測試","察看"],[15246],0.00026955179]],"測試",1]],"zh-CN",,[["Test",[1],true,false,542,0,1,0]],[["測試",1,[["Test",542,true,false],["Testing",38,true,false],["Tests",2,true,false],["Tested",0,true,false],["The test",0,true,false]],[[0,2]],"測試"]],,,[],3]

client=t //修改參數,client=j則返回json,貌似只要不是t和空的都返回json

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章