heking5201 发表于 2011-1-17 02:02:54

PHP|调用GOOGLE提供的翻译API源码

<?php
class Google_API_translator {
      public $url = "http://translate.google.com/translate_t";
      public $text = "";
      public $out = "";

      function setText($text){
            $this->text = $text;
      }

      function translate() {
            $this->out = "";

            $gphtml = $this->postPage($this->url, $this->text);

            $out = substr($gphtml, strpos($gphtml, "<div id=result_box dir=\"ltr\">"));
            $out = substr($out, 29);
            $out = substr($out, 0, strpos($out, "</div>"));

            $this->out = $out;
            return $this->out;
      }

      function postPage($url, $text) {
            $html ='';

            if($url != "" && $text != "") {
                $ch = curl_init($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);
                $fields = array('hl=zh-CN', 'langpair=zh-CN|ko', 'ie=UTF-8','text='.urlencode(mb_convert_encoding($text, 'UTF-8', 'euc-kr')));
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, implode('&', $fields));

                $html = curl_exec($ch);
                if(curl_errno($ch)) $html = "";
                curl_close ($ch);
            }
            return $html;
      }
    }

    //just for test
    $g = new Google_API_translator();
    $g->setText("사랑해");
    $g->translate();
    echo $g->out;
?>

文章来源:源码案例基地

solq360 发表于 2011-1-17 12:25:22

不错不错不错不错不错不错不错不错不错不错不错不错

solq360 发表于 2011-1-17 12:26:19

应该不用写个仿远程登陆函数吧

netloss 发表于 2011-1-28 15:49:26

heking5201 发表于 2011-1-28 17:26:21

回复 4# netloss


    测试OK正常翻译..需要换语言请自己抓包获取语言代码填写到对应的语言列表

netloss 发表于 2011-1-28 17:59:06

页: [1]
查看完整版本: PHP|调用GOOGLE提供的翻译API源码