Heim  >  Artikel  >  Backend-Entwicklung  >  php 调用google在线翻译功能_PHP教程

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

WBOY
WBOYOriginal
2016-07-20 11:06:162437Durchsuche

我们主要是用到php 调用google在线翻译功能哦,post一个远程地址再用curl读取google翻译后的值就OK了。

我们主要是用到php 调用google在线翻译功能哦,post一个远程地址再用curl读取google翻译后的值就OK了。

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返回的中文编码完全正确。
接下来,能不能反向翻译,从中文到英文哪?

 

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();


问题出现了,返回的是一个乱码。诡异的是,这次接受的是google发送过来的英文单词,怎么会有编码错误?
是php的curl无法发送unicode编码或者google在接受的过程中出现了问题吗? 复制PHP内容到剪贴板 PHP代码:echo $google_translator_url;

 

得到的url是 复制PHP内容到剪贴板 PHP代码:http://translate.google.com/translate_a/t?client=t&text=%E8%AE%A1%E7%AE%97%E6%9C%BA&sl=zh_CN&tl=en

 

直接把这个url输入浏览器的地址栏,没有任何问题(IE,Firefox均能通过)。

假设途中unicode的传送出现了解析方面的问题,在api的url上更改了一下,把"&sl=zh_CN&tl=en"更改为完全错误的参数 复制PHP内容到剪贴板 PHP代码:http://translate.google.com/translate_a/t?client=t&text=%E8%AE%A1%E7%AE%97%E6%9C%BA&sl=en&tl=en

 

奇怪了这次php页面倒是能够接受到google发回来的中文字符串,但是死活就是无法显示使用正确的编码参数google发送过来结果。


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/445056.htmlTechArticle我们主要是用到php 调用google在线翻译功能哦,post一个远程地址再用curl读取google翻译后的值就OK了。 我们主要是用到php 调用google在线翻译功...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn