Getting Started with the Google Translate API

David Ugale, Author
Written by David Ugale

The Google Translate API is a great option if you need to programmatically translate some text from one language to another.

Here is a sample PHP script that uses Curl to make a request to the Google Translate API. It sends the text “Hello, World!” in English and returns “┬íHola Mundo!” in Spanish.

<?php
/* Your Google API key */
$apiKey = 'xxxxxxxxxxxxxxxxxxx';

/* the text to translate */
$text = 'Hello, World!';

/* url to translate the text from English (en) to Spanish (es) */
$url = 'https://www.googleapis.com/language/translate/v2?key=' .
       $apiKey . '&q=' . rawurlencode($text) .
       '&source=en&target=es';

/* curl request */
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
curl_close($handle);

/* the translated text ¡Hola Mundo! */
echo $responseDecoded['data']['translations'][0]['translatedText'];
?>

To use this sample script, all you really need is a Google API key.

Originally published March 25th, 2022, updated April 21st, 2022