Google Non-AJAX Language API
I think everyone is familiar with or has heard of Google Translate, which lets you translate text. I also imagine many of you may have heard of the Google AJAX Language API:
With the AJAX Language API, you can translate and detect the language of text on web pages using only Javascript.
But sometimes you need to translate not just on the client side (using ajax), but also on the server side, by sending requests to the server through cUrl or sockets. As usual, though, Google comes through and offers a solution to our problem: Flash and other Non-Javascript Environments
Now, let’s write a simple little function:
function googleTranslater ($query, $langTo = 'en', $langFrom = 'auto', $version = '1.0') {
$url = 'http://ajax.googleapis.com/ajax/services/language/translate?'
.'v='.urlencode($version)
.'&q='.urlencode($query)
.'&langpair='.urlencode((($langFrom == 'auto')? null: $langFrom).'|'.$langTo);
$result = json_decode(file_get_contents($url));
if(is_object($result) and $result->responseStatus == 200) {
return $result->responseData->translatedText;
} else {
return false;
}
}
echo googleTranslater('С Новым Годом!');
The data is returned in UTF-8.
UPDATE:
That’s it, I admit defeat at the hands of Mavr and his Google translator. His can send 32 KB via POST; mine, a little over 2 KB via GET. No matter how much I tried rewriting it, Google wouldn’t let me send more than 2 KB at a time and wouldn’t allow POST. Still, I didn’t waste my time: along the way I also learned the Google AJAX Search API, and now I’ll put those skills to use in two other projects!
UPDATE:
LivePad: Google translate
Google_translate PHP class
UPDATE:
Comments are closed. Read the original discussion in Russian →