Google translate

Автор: Google translate Написано: 1 г. назад Форматирование: php.
Без нумерации строк
  1. <?php
  2. class Google_API_translator {
  3.     public $opts = array("text" => "", "language_pair" => "en|it");
  4.     public $out = "";
  5.  
  6.     function __construct() {
  7.     }
  8.  
  9.     function setOpts($opts) {
  10.         if($opts["text"] != "") $this->opts["text"] = $opts["text"];
  11.         if($opts["language_pair"] != "") $this->opts["language_pair"] = $opts["language_pair"];
  12.     }
  13.  
  14.     function translate() {
  15.         $this->out = "";
  16.         $google_translator_url = "http://translate.google.com/translate_t?langpair=".urlencode($this->opts["language_pair"])."&amp;";
  17.         $google_translator_data .= "text=".urlencode($this->opts["text"]);
  18.         $gphtml = $this->postPage(array("url" => $google_translator_url, "data" => $google_translator_data));
  19.         $out = substr($gphtml, strpos($gphtml, "<div id=result_box dir=\"ltr\">"));
  20.         $out = substr($out, 29);
  21.         $out = substr($out, 0, strpos($out, "</div>"));
  22.         $this->out = $out;
  23.         return $this->out;
  24.     }
  25.  
  26.     // post form data to a given url using curl libs
  27.     function postPage($opts) {
  28.         $html = "";
  29.         if($opts["url"] != "" && $opts["data"] != "") {
  30.             $ch = curl_init($opts["url"]);
  31.             curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  32.             curl_setopt($ch, CURLOPT_HEADER, 1);
  33.             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  34.             curl_setopt($ch, CURLOPT_TIMEOUT, 15);
  35.             curl_setopt($ch, CURLOPT_POST, 1);
  36.             curl_setopt($ch, CURLOPT_POSTFIELDS, $opts["data"]);
  37.             $html = curl_exec($ch);
  38.             if(curl_errno($ch)) $html = "";
  39.             curl_close ($ch);
  40.         }
  41.         return $html;
  42.     }
  43. }
  44. $g = new Google_API_translator();
  45. $text=$_GET['text'];
  46. $g->setOpts(array("text" => $text, "language_pair" => "en|uk"));
  47. $g->translate();
  48. $text=$g->out;
  49. print $text;
  50. ?>
Теги: google, translate