PHP使用Google的translate API

这里我还是接上话使用Google的translate工具翻译 .NET translate API的一篇文字,上篇是c#实现的,我这里再用PHP实现一下。新建一个ANSI的PHP文件,然后创建一个类:

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

class Google_API_translator{
    public $opts = array("text" => "", "language_pair" => "en|it");
    public $out = "";

    function setOpts($opts) {
        if($opts["text"] != "") $this->opts["text"] = $opts["text"];
        if($opts["language_pair"] != "") $this->opts["language_pair"] = $opts["language_pair"];
    }

    function translate() {
        $this->out = "";
        $google_translator_url = "
        $google_translator_data .= "text=".urlencode($this->opts["text"]);
        $gphtml = $this->postPage(array("url" => $google_translator_url, "data" => $google_translator_data));
        $out = substr($gphtml, strpos($gphtml, "

"));
        $out = substr($out, 29);
        $out = substr($out, 0, strpos($out, "
"));
        $this->out = utf8_encode($out);
        return    $this->out;
    }

    function postPage($opts) {
        $html ='';
        if($opts["url"] != "" && $opts["data"] != "") {
            $ch = curl_init($opts["url"]);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 15);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $opts["data"]);
            $html = curl_exec($ch);
            if(curl_errno($ch)) $html = "";
            curl_close ($ch);
        }
        return $html;
    }
}
?>

使用的时候

$g = new Google_API_translator();
$g->setOpts(array("text" => "Cjjer是天才", "language_pair" => "zh-CN|en"));
$g->translate();
echo $g->out;
?>

这样就可以了,输出:Cjjer is genius

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/14883374/viewspace-442972/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/14883374/viewspace-442972/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值