Access Google Translate API with PHP

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").

8 thoughts on “Access Google Translate API with PHP

  1. Pingback: Use Google Translate from the command-line with resty | CompleteFusion

  2. George

    Hello,

    thanks for valuable piece of code.

    One problem not solved (I am not a php guru): it works for small text (like maximum 20 words); for text larger than about 20 words the script return error

    Fatal error: Cannot use string offset as an array in C:\xampp\htdocs\test\translate.php on line 23
    //line 23 is the same as above

    If you may help, I really appreciate.

  3. admin Post author

    @George Could you supply your test string? I've successfully tested text as long as ~2500 characters (300+ words). That error seems to indicate a problem with the JSON response.

  4. 7segment

    Hi,

    Does the API return the alternative translations of words as in Google Translate itself? Or can you suggest a way to tackle the problem? I have tried many ways, excluding the use of the API, such as reading the whole web page and trying to find the tags containing the data i need, but they are empty!

    Any help appreciated.

    J

  5. reza

    My problem is like George. The error message is Fatal error: Cannot use string offset as an array in C:\AppServ\www\translate\TranslateCSV.php on line 23. But in other computer, the program can run. I'm using AppServ as Web Server.

Leave a Reply

Your email address will not be published. Required fields are marked *