码迷,mamicode.com
首页 > Web开发 > 详细

php调用google在线翻译功能

时间:2014-12-27 11:25:10      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

php调用google在线翻译功能

从中文到英语

class Google_API_translator {
    public $out = "";
    function translate() {
        $this->out = "";
        $text = urlencode("计算机");//要翻译的单词
        $google_translator_url = "http://translate.google.com/translate_a/t?client=t&text=".$text."&sl=zh_CN&tl=en";
        echo $google_translator_url;
        $gphtml = $this->postPage(array("url" => $google_translator_url));
        $this->out = $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();


从英语到中文

class Google_API_translator {
    public $out = "";
    function translate() {
        $this->out = "";
        $text = urlencode("computer");//要翻译的单词
        $google_translator_url = "http://translate.google.com/translate_a/t?client=t&text=".$text."&sl=en&tl=zh_CN";
        //拼凑google翻译的api url         
        $gphtml = $this->postPage(array("url" => $google_translator_url));
        $this->out = $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();

很完美,返回的结果中没有任何编码问题。从google返回的中文编码完全正确。

php调用google在线翻译功能

标签:

原文地址:http://www.cnblogs.com/afish/p/4188117.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!