Recently I wanted to utilize Google's translation API, so I came up with the following PHP script. Please note that I didn't build in any error handling, debugging code, security measures, or the full range of features of the Google translation API.. all of which you should probably do if you're going to use this in a public or production environment.
Create a new .php file on your web server, as follows:
// Basic request parameters: // s = source language // d = destination language // q = Text to be translated $s = $_REQUEST['s']; $d = $_REQUEST['d']; $lang_pair = urlencode($s.'|'.$d); $q = urlencode($_REQUEST['q']); // Google's API translator URL $url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=".$q."&langpair=".$lang_pair; // Make sure to set CURLOPT_REFERER because Google doesn't like if you leave the referrer out $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_REFERER, "http://www.yoursite.com/translate.php"); $body = curl_exec($ch); curl_close($ch); $json = json_decode($body, true); echo $json['responseData']['translatedText'];
Then just load up http://www.yoursite.com/translate.php?s=en&d=es&q=Test and you should see "Prueba" (Spanish for "Test").