当前位置:编程学习 > php >>

php 调用google在线翻译功能

我们主要是用到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发送过来结果。

补充:Php教程,Php高级应用 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,