I recently wrote a quick PHP class to do some content translation via the Google AJAX Language API, and thought it may be useful for others.
It is by no means a complete class for the API, and in fact only uses one of its methods (language.translate).
The ‘AJAX’ part of the API name is also mis-leading in this case, as we will not be sending an AJAX request or even using and Client Side code – but rather using CURL on the server side to access the API and then dedode the JSON objects using PHP.
I would recommend extending it to include some kind of file or database driven caching system if you will be using it on a high traffic site or translating entire web pages rather than just snippets. Also be sure to abide by Google’s Terms of Use
Here it is:
<?php
/**
* Translate text via the google translate API
*
* @version 1.0
* @author Chris Wheeler <chris@haydendigital.com>
* @copyright Chris Wheeler
* @date: 2010-07-15
*
* Usage:
*
* $translator = new googletranslate();
* $translator->translate('en', 'fr', 'Hello World!');
*
* Full list of supported languages is at http://code.google.com/apis/ajaxlanguage/documentation/reference.html#LangNameArray
* GOOGLE_SEARCH_API key should be defined with a valid Google Search API key for the domain
*
*/
class googletranslate {
/**
* POSTs the text to be translated to the API
*
* @return String
*/
private function postmessage($url, $text){
set_time_limit(30);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, "q=" . urlencode($text));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
$response = preg_split('/' . chr(10) . '/', curl_exec($curl));
if ($error = curl_error($curl)){
throw new Exception('CURL Error: ' . $error);
}
curl_close ($curl);
return implode($response);
}
/**
* Translte
*
* @return String
*/
public function translate($from, $to, $text) {
try {
if (strlen($text) == 0) {
throw new Exception('Empty string.');
}
if (strlen($text) > 5000) {
throw new Exception('Text to be translated is too long.');
}
$url = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair=' . $from . '%7C' . $to . '&key=' . GOOGLE_SEARCH_APIKEY . '&userip=' . $_SERVER['REMOTE_ADDR'];
$jsonresponse = $this->postmessage($url, $text);
$response = json_decode($jsonresponse, true);
if ($response['responseStatus'] == 200) {
$responsedata = $response['responseData'];
return $responsedata['translatedText'];
}
} catch (Exception $e) {
// Handle errors if required
}
return false;
}
}
?>