首页  >  文章  >  后端开发  >  php调用google在线翻译功能_PHP教程

php调用google在线翻译功能_PHP教程

WBOY
WBOY原创
2016-07-20 11:06:221501浏览

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返回的中文编码完全正确。


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/445043.htmlTechArticlephp调用google在线翻译功能 从中文到英语 class Google_API_translator { public $out = ; function translate() { $this-out = ; $text = urlencode(计算机);//要翻译的单词...
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn