PHP: Google Translate (CURL)
Альтернатива, которую пришлось искать после перевода на платную основу Google Translate API.
Источник: http://habrahabr.ru/blogs/php/120174/
Проект на GihHub: https://github.com/Andrew8xx8/GoogleTranslater
Исходники:
<?php
/**
* GoogleTranslater is PHP interface for http://translate.google.com/
* It send request to google translate service, get response and provide
* translated text.
*
* @author Andrew Kulakov <[email protected]>
* @version 1.0.0
* @license https://github.com/Andrew8xx8/GoogleTranslater/blob/master/MIT-LICENSE.txt
* @copyright Andrew Kulakov (c) 2011
*/
class GoogleTranslater
{
/**
* @var string Some errors
*/
private $_errors = "";
/**
* Constructor
*/
public function _construct()
{
if (!function_exists('curl_init'))
$this->_errors = "No CURL support";
}
/**
* Translate text.
* @param string $text Source text to translate
* @param string $fromLanguage Source language
* @param string $toLanguage Destenation language
* @param bool $translit If true function return transliteration of source text
* @return string|bool Translated text or false if exists errors
*/
public function translateText($text, $fromLanguage = "en", $toLanguage = "ru", $translit = false)
{
if (empty($this->_errors)) {
$result = "";
for($i = 0; $i < strlen($text); $i += 1000)
{
$subText = substr($text, $i, 1000);
$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");
$result .= $this->_parceGoogleResponse($response, $translit);
// sleep(1);
}
return $result;
} else
return false;
}
/**
* Translate array.
* @param array $array Array with source text to translate
* @param string $fromLanguage Source language
* @param string $toLanguage Destenation language
* @param bool $translit If true function return transliteration of source text
* @return array|bool Array with translated text or false if exists errors
*/
public function translateArray($array, $fromLanguage = "en", $toLanguage = "ru", $translit = false)
{
if (empty($this->_errors)) {
$text = implode("[<#>]", $array);
$response = $this->translateText($text, $fromLanguage, $toLanguage, $translit);
return $this->_explode($response);
} else
return false;
}
public function getLanguages()
{
if (empty($this->_errors)) {
$page = $this->_curlToGoogle('http://translate.google.com/');
preg_match('%<select[^<]*?tl[^<]*?>(.*?)</select>%is', $page, $match);
preg_match_all("%<option.*?value=\"(.*?)\">(.*?)</option>%is", $match[0], $languages);
$result = Array();
for($i = 0; $i < count($languages[0]); $i++){
$result[$languages[1][$i]] = $languages[2][$i]);
}
return $result;
} else
return false;
}
public function getLanguagesHTML()
{
if (empty($this->_errors)) {
$page = $this->_curlToGoogle('http://translate.google.com/');
preg_match('%<select[^<]*?tl[^<]*?>(.*?)</select>%is', $page, $match);
return $match[1];
} else
return false;
}
public function getErrors()
{
return $this->_errors;
}
private function _explode($text)
{
$text = preg_replace("%\[\s*<\s*#\s*>\s*\]%", "[<#>]", $text);
return array_map('trim', explode('[<#>]', $text));
}
private function _curlToGoogle($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
if (isset($_SERVER['HTTP_REFERER'])) {
curl_setopt($curl, CURLOPT_REFERER, $_SERVER['HTTP_REFERER']);
}
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");
$response = curl_exec($curl);
// Check if any error occured
if(curl_errno($curl))
{
$this->_errors .= "Curl Error: ".curl_error($curl);
return false;
}
curl_close($curl);
return $response;
}
private function _parceGoogleResponse($response, $translit = false)
{
if (empty($this->_errors)) {
$result = "";
$json = json_decode($response);
foreach ($json->sentences as $sentence) {
$result .= $translit ? $sentence->translit : $sentence->trans;
}
return $result;
} else {
return false;
}
}
}
?>
Использование:
<?php
/**
* Sample. How to use GoogleTranslater.
*
* @author Andrew Kulakov <[email protected]>
* @version 1.0.0
* @license https://github.com/Andrew8xx8/GoogleTranslater/blob/master/MIT-LICENSE.txt
* @copyright Andrew Kulakov (c) 2011
* @licenze CI
*/
require_once("GoogleTranslater.php");
// Create GT Object
$gt = new GoogleTranslater();
// Translate text
// Usage: GoogleTranslater :: translateText(string $text, string $fromLanguage, string $tolanguage, bool $translit = false)
$translatedText = $gt->translateText("
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.
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
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.
", "en", "ru");
if ($translatedText !== false) {
echo $translatedText;
} else {
//If some errors present
echo $gt->getErrors();
}
// Crasy stuff. Translate array
// Usage: GoogleTranslater :: translateArray(array $array, string $fromLanguage, string $tolanguage, bool $translit = false)
$translatedArray = $gt->translateArray(array("Some", "Words", "To", "Translate"), "en", "ru");
if ($translatedArray !== false) {
print_r($translatedArray);
} else {
echo $gt->getErrors();
}
?>
Опечатка (убрать закрывающуюся скобку):
$result[$languages[1][$i]] = $languages[2][$i];
Спасибо автору.
Edit lines to:
and
For me works fine :)
46-я строка… Да что ты будешь делать!))) Большие тексты переводить им невозможно, ибо текст для перевода нужно POST-ом передавать, а в классе гетом описано. В принципе, несложно допилить класс, но я уже свою маленькую функцию написал…
From ru->en not work :(
thanks
Сам нашел ошибку ))
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)
Parse error: parse error in C:\htdocs\www\trans\GoogleTranslater.php on line 80
???