Google Translation PHP wrapper

UPDATE
Google has deprecated its Translation service, hence it will not be available for download anymore.

Google translation is an interesting service. Not only can you do language translation, you can also detect the language of a particular text. I recently needed to create a WordPress plugin to translate post titles from one language to another. As the translation API is only available for Java and Javascript, I decided to create a quick one for PHP. In this post we will see how to translate text from one language to another in a simple and quick way using the created class.

Getting the class

Before we begin you need to get the PHP class from below.

Testing the class

The Translation class used cURL to access the Google translation service, so you need to have that installed. A quick way to check if the class is working correctly is to use the ‘selfTest’ method of the class.

<?php
 
require_once('googleTranslate.class.php');
 
$gt = new GoogleTranslateWrapper();
$gt->selfTest();
 
?>

Which will print ‘Test Ok’ if everything is working fine.

Translating text

Once you are sure that the class is working properly, you can use the following simple example to translate a piece of text from one language to another.

<?php
 
require_once('googleTranslate.class.php');
 
/* Initialize the class translate class */
$gt = new GoogleTranslateWrapper();
$sampleText = "Bonjour de cette partie du monde";
 
/* translate(string, to_language, from_language) */
echo $gt->translate($sampleText , "en", "fr");
 
/* This should print 'Hello from this part of the world' */
 
?>

The first parameter of the ‘translate()’ method takes the text to translate, the second and third parameters take the target language to translate to and the language to translate from, respectively. You can eliminate the third parameter, the language name to translate from, and Google will automatically detect the source language and translate the text. This can be useful if you are not sure of the source language but want to translate and also detect the same. A short example is given below. The following will convert the sample text and also detect the source language (French here).

<?php
 
require_once('googleTranslate.class.php');
 
$gt = new GoogleTranslateWrapper();
$test = "Bonjour de cette partie du monde";
/* Convert from English */
$gt->translate($test, "en");
echo $gt->getDetectedSource();
 
?>

Errors during translation

If the class fails to translate the text for some reason, you can read the error message using the ‘getLastError’ method.

.
.
echo $gt->getLastError();
.

The class also provides the ‘isSuccess’ method to check if the translation was successful.

/* Was translation successful */
if(!$gt->isSuccess()) {
    echo $gt->getLastError();
}

Detecting language of a text block

You can also detect the language of a particular text block as shown below. This can be quite useful if you would like to detect the language of a web page or a block of a chat conversation.

<?php
 
require_once('googleTranslate.class.php');
$gt = new GoogleTranslateWrapper();
 
/* Detect the language of the given text */
$text = "For me, it is far better to grasp
        the Universe as it really is than
        to persist in delusion, however
        satisfying and reassuring.";
 
print_r($gt->detectLanguage($text));
 
?>

This will output an array with the following response elements:

[language] => en
[isReliable] => 1
[confidence] => 0.7626736

The first index gives the language code for the given text block. The second index represents a boolean value showing whether or not the detected language code is reliable for the given text. The third and last parameter is a numeric value between 0 – 1.0 that represents the confidence level in the language detected for the given text.

Caching

The class also has the facility to cache the results, so if you post a text for translation and it is already in the cache the cached results will be returned instead of going out to Google for translation, this helps decrease translation time. The cache can be enabled or disabled as below, by default the cache is enabled.

<?php
require_once('googleTranslate.class.php');
 
$gt = new GoogleTranslateWrapper();
/* Enable the cache */
$gt->cacheEnabled(true);
 
/* This will disable the cache; by default the cache is enabled */
$gt->cacheEnabled(false);
?>

Make sure that the ‘cache’ directory is there in the directory where your php file is located. If you need to locate the ‘cache’ directory somewhere different than you can change it in the ‘googleTranslate.class.php’ file. Locate the following line in the file, and then change the directory path to the one you want.

private $_cache_directory = './cache/';

Setting correct Referer header

Google requires that you send the referrer header with every request. Although it works without it, it is recommended that you use it. You can add a referrer header as below:

.
.
$gt = new GoogleTranslateWrapper();
$gt->setReferrer("http://www.your_site_name.com");
.
.

This sends your site name in the ‘Referer’ header in the request.

Passing valid credentials

Although the class works without you providing a apiKey – using a key in your application/site is completely optional, Google recommends adding your API key and a IP address during the translation request. This helps Google detect valid requests coming from your site and helps it in contacting you in case a need arises. You can signup for the api key here.

You can pass a API key and a IP address using the following.

<?php
 
require_once('googleTranslate.class.php');
 
$apiKey = "YOUR API KEY";
/* Change to your IP address */
$ip = "127.0.0.1";
 
$gt = new GoogleTranslateWrapper();
 
$gt->setCredentials($apiKey, $ip);
$test = "mon nom est Sameer";
echo $gt->translate($test, "en");
 
?>

Passing correct content headers

Make sure you have the following code at the start of your php code:

<?php
 
header("Content-type: text/html; charset=utf-8");
.
.

or if the page is html, the following in your head tags:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Not setting the correct content type will display gibberish characters for Chinese and texts that have special characters.

Language Codes

Below is a list of language codes you can use during translation.

"af"-Afrikaans
"sq"-Albanian
"ar"-Arabic
"hy"-Armenian ALPHA
"az"-Azerbaijani ALPHA
"eu"-Basque ALPHA
"be"-Belarusian
"bg"-Bulgarian
"ca"-Catalan
"zh-CN"-Chinese
"hr"-Croatian
"cs"-Czech
"da"-Danish
"nl"-Dutch
"en"-English
"et"-Estonian
"tl"-Filipino
"fi"-Finnish
"fr"-French
"gl"-Galician
"ka"-Georgian ALPHA
"de"-German
"el"-Greek
"ht"-Haitian Creole ALPHA
"iw"-Hebrew
"hi"-Hindi
"hu"-Hungarian
"is"-Icelandic
"id"-Indonesian
"ga"-Irish
"it"-Italian
"ja"-Japanese
"ko"-Korean
"lv"-Latvian
"lt"-Lithuanian
"mk"-Macedonian
"ms"-Malay
"mt"-Maltese
"no"-Norwegian
"fa"-Persian
"pl"-Polish
"pt"-Portuguese
"ro"-Romanian
"ru"-Russian
"sr"-Serbian
"sk"-Slovak
"sl"-Slovenian
"es"-Spanish
"sw"-Swahili
"sv"-Swedish
"th"-Thai
"tr"-Turkish
"uk"-Ukrainian
"ur"-Urdu ALPHA
"vi"-Vietnamese
"cy"-Welsh
"yi"-Yiddish


63 thoughts on “Google Translation PHP wrapper

  1. nope,it does not print anything.

    require_once(‘./googleTranslate.class.php’);
    $gt = new GoogleTranslateWrapper();
    $gt->selfTest();
    //echo “ab-“.$gt->getLastError().”+cd”;

    I get ‘Test Failed.’ onscreen

    require_once(‘./googleTranslate.class.php’);
    $gt = new GoogleTranslateWrapper();
    //$gt->selfTest();
    echo “ab-“.$gt->getLastError().”+cd”;

    I get ‘ab-+cd’ onscreen

  2. i used your code but it prints on localhost but it does not print on online. Can you give me any solution

  3. I there mate. great nice clean code.

    One question: the API manages requests for text or HTML content, to preserve HTML tags into translation.

    How do you cope splitting blocks larger than 5000 chars, avoiding split in between html “open” tags?

  4. Well, the current code just splits the text at the 5000 char boundary, I tested on a few html pages which split the text right in between tags, and translated them correctly.

  5. i downloaded your class and run example.php file nothing is display in browser, when i run samplecode of selftest() available on your website [cURL not installed] error comes………..

    any solution

  6. What are the language options?

    en is english
    fr is french

    how about spanish?
    other languages?

    Thanks

  7. Is there a way to easily incorporate the other languages Google provides translation services for? The list you provided is fantastic and extremely comprehensive, but I was hoping (just for fun) to be able to add Elmer Fudd, Klingon, etc. translations to my site, however, specifying any of those (xx-elmer, xx-klingon, etc.) returns no content.

Comments are closed.