免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1970 | 回复: 0
打印 上一主题 下一主题

google translation api [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-03-21 10:53 |只看该作者 |倒序浏览

?php
class Google_API_translator {
    public $opts = array("text" => "", "language_pair" => "en|it");
    public $out = "";
    function __construct() {
        echo "Google Translator API\n(c) 2007 Involutive snc http://www.involutive.com\n";
        echo "Author: Paolo Ardoino ";
    }
    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 = "http://translate.google.com/translate_t?langpair=".urlencode($this->opts["language_pair"])."&";
        $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;
    }
    // post form data to a given url using curl libs
    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;
    }
}
?>
?php
$g = new Google_API_translator();
$g->setOpts(array("text" => "ciao", "language_pair" => "it|en"));
$g->translate();
echo $g->out;
?>













本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/25698/showart_502118.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP