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 = "".$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, "");
$body = curl_exec($ch);
$json = json_decode($body, true);
echo $json['responseData']['translatedText'];

Then just load up 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


    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


    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.


  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 *