Главная > PHP, Web > PHP: Google Translate (CURL)

PHP: Google Translate (CURL)

Альтернатива, которую пришлось искать после перевода на платную основу Google Translate API.

Источник: http://habrahabr.ru/blogs/php/120174/

Проект на GihHub: https://github.com/Andrew8xx8/GoogleTranslater

Исходники:

  1. <?php
  2. /**
  3.  * GoogleTranslater is PHP interface for http://translate.google.com/
  4.  * It send request to google translate service, get response and provide 
  5.  * translated text.
  6.  *
  7.  * @author Andrew Kulakov <[email protected]>
  8.  * @version 1.0.0
  9.  * @license https://github.com/Andrew8xx8/GoogleTranslater/blob/master/MIT-LICENSE.txt
  10.  * @copyright Andrew Kulakov (c) 2011
  11.  */
  12.  
  13. class GoogleTranslater 
  14. {
  15.     /**
  16.      * @var string Some errors
  17.      */
  18.     private $_errors = "";
  19.  
  20.     /**
  21.      * Constructor
  22.      */
  23.     public function _construct() 
  24.     {
  25.         if (!function_exists('curl_init'))
  26.             $this->_errors = "No CURL support";
  27.     }   
  28.  
  29.     /**
  30.      * Translate text.
  31.      * @param  string $text          Source text to translate
  32.      * @param  string $fromLanguage  Source language
  33.      * @param  string $toLanguage    Destenation language
  34.      * @param  bool   $translit      If true function return transliteration of source text 
  35.      * @return string|bool           Translated text or false if exists errors
  36.      */
  37.     public function translateText($text, $fromLanguage = "en", $toLanguage = "ru", $translit = false) 
  38.     {
  39.         if (empty($this->_errors)) {
  40.             $result = "";
  41.             for($i = 0; $i < strlen($text); $i += 1000)
  42.             {
  43.                 $subText = substr($text, $i, 1000);
  44.  
  45.                 $response = $this->_curlToGoogle("http://translate.google.com/translate_a/t?client=te&text=".urlencode($subText)."&hl=ru&sl=$fromLanguage&tl=i$toLanguage&multires=1&otf=1&ssel=0&tsel=0&uptl=ru&sc=1");
  46.                 $result .= $this->_parceGoogleResponse($response, $translit);
  47. //                sleep(1); 
  48.             }
  49.             return $result;
  50.         } else
  51.             return false;
  52.     } 
  53.  
  54.     /**
  55.      * Translate array.
  56.      * @param  array  $array         Array with source text to translate
  57.      * @param  string $fromLanguage  Source language
  58.      * @param  string $toLanguage    Destenation language
  59.      * @param  bool   $translit      If true function return transliteration of source text 
  60.      * @return array|bool            Array  with translated text or false if exists errors
  61.      */     
  62.     public function translateArray($array, $fromLanguage = "en", $toLanguage = "ru", $translit = false) 
  63.     {
  64.         if (empty($this->_errors)) {
  65.             $text = implode("[<#>]", $array);
  66.             $response = $this->translateText($text, $fromLanguage, $toLanguage, $translit);
  67.             return $this->_explode($response);
  68.         } else
  69.             return false;
  70.     }
  71.  
  72.     public function getLanguages()
  73.     {
  74.         if (empty($this->_errors)) {
  75.             $page = $this->_curlToGoogle('http://translate.google.com/');
  76.             preg_match('%<select[^<]*?tl[^<]*?>(.*?)</select>%is', $page, $match);
  77.             preg_match_all("%<option.*?value=\"(.*?)\">(.*?)</option>%is", $match[0], $languages);
  78.             $result = Array();
  79.             for($i = 0; $i < count($languages[0]); $i++){
  80.                 $result[$languages[1][$i]] = $languages[2][$i]);
  81.             }
  82.             return $result;           
  83.         } else                 
  84.             return false; 
  85.     }
  86.  
  87.     public function getLanguagesHTML()
  88.     {
  89.         if (empty($this->_errors)) {
  90.             $page = $this->_curlToGoogle('http://translate.google.com/');
  91.             preg_match('%<select[^<]*?tl[^<]*?>(.*?)</select>%is', $page, $match);
  92.             return $match[1];
  93.         } else                 
  94.             return false; 
  95.     }
  96.  
  97.     public function getErrors()
  98.     {
  99.         return $this->_errors;
  100.     }
  101.  
  102.     private function _explode($text)
  103.     {        
  104.         $text = preg_replace("%\[\s*<\s*#\s*>\s*\]%", "[<#>]", $text);
  105.         return array_map('trim', explode('[<#>]', $text));
  106.     }
  107.  
  108.     private function _curlToGoogle($url)
  109.     {
  110.         $curl = curl_init();
  111.         curl_setopt($curl, CURLOPT_URL, $url);
  112.         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  113.         if (isset($_SERVER['HTTP_REFERER'])) {
  114.             curl_setopt($curl, CURLOPT_REFERER, $_SERVER['HTTP_REFERER']);
  115.         }
  116.         curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.71 Safari/534.24");  
  117.         $response = curl_exec($curl);
  118.         // Check if any error occured
  119.         if(curl_errno($curl))
  120.         {
  121.             $this->_errors .=  "Curl Error: ".curl_error($curl);
  122.             return false;
  123.         }
  124.         curl_close($curl);
  125.         return $response;
  126.     }
  127.  
  128.     private function _parceGoogleResponse($response, $translit = false)
  129.     {
  130.         if (empty($this->_errors)) {
  131.             $result = "";            
  132.             $json = json_decode($response);           
  133.             foreach ($json->sentences as $sentence) {
  134.                 $result .= $translit ? $sentence->translit : $sentence->trans;  
  135.             }
  136.             return $result;
  137.         }  else {
  138.             return false;
  139.         }
  140.     }
  141. }
  142. ?>

Использование:

  1. <?php
  2. /**
  3.  * Sample. How to use GoogleTranslater.
  4.  *
  5.  * @author Andrew Kulakov <[email protected]>
  6.  * @version 1.0.0
  7.  * @license https://github.com/Andrew8xx8/GoogleTranslater/blob/master/MIT-LICENSE.txt
  8.  * @copyright Andrew Kulakov (c) 2011
  9.  * @licenze CI
  10.  */ 
  11.  
  12. require_once("GoogleTranslater.php");
  13.  
  14. // Create GT Object
  15.     $gt = new GoogleTranslater();
  16.  
  17. // Translate text
  18. // Usage: GoogleTranslater :: translateText(string $text, string $fromLanguage, string $tolanguage, bool $translit = false)
  19. $translatedText = $gt->translateText("
  20.     English literature is the literature written in the English language, including literature composed in English by writers not necessarily from England; for example, Robert Burns was Scottish, James Joyce was Irish, Joseph Conrad was born in Poland, Dylan Thomas was Welsh, Edgar Allan Poe was American, V.S. Naipaul was born in Trinidad, and Vladimir Nabokov was Russian, but all are considered important writers in the history of English literature. In other words, English literature is as diverse as the varieties and dialects of English spoken around the world. In academia, the term often labels departments and programmes practising English studies in secondary and tertiary educational systems. Despite the variety of authors of English literature, the works of William Shakespeare remain paramount throughout the English-speaking world.
  21.     This article primarily deals with some of the literature from Britain written in English. For literature from specific English-speaking regions, consult the see also section, bottom of the page
  22.     The first works in English, written in Old English, appeared in the early Middle Ages (the oldest surviving text is Cædmon's Hymn). The oral tradition was very strong in the early English culture and most literary works were written to be performed. Epic poems were thus very popular and many, including Beowulf, have survived to the present day in the rich corpus of Anglo-Saxon literature that closely resemble today's Icelandic, Norwegian, North Frisian and the Northumbrian and Scots English dialects of modern English. Much Old English verse in the extant manuscripts is probably a milder adaptation of the earlier Germanic war poems from the continent. When such poetry was brought to England it was still being handed down orally from one generation to another, and the constant presence of alliterative verse, or .consonant rhyme (today's newspaper headlines and marketing abundantly use this technique such as in Big is Better) helped the Anglo-Saxon people remember it. Such rhyme is a feature of Germanic languages and is opposed to vocalic or end-rhyme of Romance languages. But the first written literature dates to the early Christian monasteries founded by St. Augustine of Canterbury and his disciples and it is reasonable to believe that it was somehow adapted to suit to needs of Christian readers.
  23.     ", "en", "ru");
  24.     if ($translatedText !== false) {
  25.         echo $translatedText;
  26.     } else {
  27.         //If some errors present
  28.         echo $gt->getErrors(); 
  29.     }
  30.  
  31. // Crasy stuff. Translate array
  32. // Usage: GoogleTranslater :: translateArray(array $array, string $fromLanguage, string $tolanguage, bool $translit = false)
  33.     $translatedArray = $gt->translateArray(array("Some", "Words", "To", "Translate"), "en", "ru");
  34.     if ($translatedArray !== false) {
  35.         print_r($translatedArray);
  36.     } else {
  37.         echo $gt->getErrors(); 
  38.     }    
  39. ?>

Опечатка (убрать закрывающуюся скобку):

  1. $result[$languages[1][$i]] = $languages[2][$i];

Спасибо автору.

Categories: PHP, Web Tags: ,
  1. MateuszRyaN
    8 марта,2013 в 10:12 | #1

    Edit lines to:

    public function translateArray($array, $fromLanguage, $toLanguage, $translit = false)

    and

    $response = $this->_curlToGoogle("http://translate.google.com/translate_a/t?client=te&text=".urlencode($subText)."&hl=$toLanguage&sl=$fromLanguage&tl=i$toLanguage&multires=1&otf=1&ssel=0&tsel=0&uptl=$toLanguage&sc=1");

    For me works fine :)

  2. Андрей
    28 ноября,2012 в 16:41 | #2

    46-я строка… Да что ты будешь делать!))) Большие тексты переводить им невозможно, ибо текст для перевода нужно POST-ом передавать, а в классе гетом описано. В принципе, несложно допилить класс, но я уже свою маленькую функцию написал…

  3. mihail
    6 ноября,2012 в 23:08 | #3

    From ru->en not work :(

  4. Аноним
    20 марта,2012 в 23:47 | #4

    thanks

  5. TJ
    21 февраля,2012 в 12:41 | #5

    Сам нашел ошибку ))
    XAMPP
    ;extension=php_curl.dll to extension=php_curl.dll in
    C:\Program Files\xampp\apache\bin\php.ini
    C:\Program Files\xampp\php\php.ini
    C:\Program Files\xampp\php\php4\php.ini
    okaY)

  6. TJ
    21 февраля,2012 в 11:51 | #6

    Parse error: parse error in C:\htdocs\www\trans\GoogleTranslater.php on line 80
    ???

Похожие публикации