Wind__Fantasy

导航

[短文本]免费版google翻译(PHP)

google翻译api要收费了, 所以想法写了个免费版本的google翻译:

 

<?php


  /**
   * translate [short] text from source language to target language using google translate proxy
   * be careful if google data type or url has been modified
   */
  class GoogleTranslater
  {
    protected $text, $source, $target, $url, $holder;
    const REMOTE_TRANSLATE_URL='http://translate.google.com/translate_a/t?client=t&text=%TEXT%&hl=de&sl=%SL%&tl=%TL%&multires=1&otf=2&ssel=3&tsel=3&sc=1';
    public function __construct($text, $source='en', $target='de')
    {
      $this->source=$source;
      $this->target=$target;
      $this->text=$text;
      $this->holder=array();
      $this->url=str_replace(array('%TEXT%', '%SL%', '%TL%'), array($text, $source, $target), self::REMOTE_TRANSLATE_URL);
    }
    public function getTranslateResult()
    {
      $ch=curl_init($this->url);
      curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
      curl_setopt($ch, CURLOPT_REFERER, 'http://translate.google.com/');
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
      $response = curl_exec($ch);
      curl_close($ch);
      $json = json_decode(preg_replace('/,{2,}/', ',', $response), true);
      return ($json && isset($json[0]) && isset($json[0][0]) && isset($json[0][0][0])) ? $json[0][0][0] : null;
    }
  }
  $gt = new GoogleTranslater('你好, 世界!', 'zh', 'en');
  $r = $gt->getTranslateResult();
  echo "$r\n";
?>

 

 输出为: Hello , world !

 替换'你好, 世界!'为其他的中文运行试试看

posted on 2012-02-21 15:38  Wind__Fantasy  阅读(1025)  评论(2编辑  收藏  举报