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.

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.

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

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.

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.

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.

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:


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


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 to “Google Translation PHP wrapper”

  1. Good to see the Google Translate API taking shape. All I need now is a API key and I can start to include this in some projects.

  2. Thanks for this example. helped me a lot. I have 1 problem, I am translating chunks of code, but I don’t get a correct return when a new line is sent. netierh \r nor \n are returned.
    Do you know why maybe?

  3. hi,
    nice post………..i would like to read a post on google transliteration as i am currently doing a project on transliteration it will be a great help if you share your knowledge on that

    thankyou for such a good post

  4. Thanks so much for this – – works great. I am using this is large Drupal site that is under development.

    I need to add the following capability but cannot see how:

    I need to call google and obtain the current list of languages.

    I see that google provides this in the context of their ajax-delivered pages

    So:
    1) do you know how to obtain this list – – hopefully as a key-value array (where the key would be aligned with iso639-2)?

    2) if, so, what is best way to integrate this into your wrapper?

    Hugely grateful – also, am gald to return favor-in-kind!

  5. Hello Stephen!

    Google doesn’t provide a API to get the translatable languages. A workaround is to use the Javascript API and get the list of languages, which you can then pass on to the server side php code. Note that the languages doesn’t change much, so you can add a ‘key:value’ array to the GoogleTranslate class code once and update it frequently.

    A short code to print the languages list is given below:

    http://pastie.org/905240

  6. Hello Sameer,

    First, thanks for this. It works like a charm. I am running into a small problem though. Non-English characters are not being returned correctly. Which is to say, accented characters in French, such as ê, are returned as è. And simplified Chinese showed up as: 我饿了。. I’m just wondering if this was something odd in the class code, or the way it’s being interpreted by my PHP code (which is not doing anything to the returned translation).

    I went to the Google Translate page (http://translate.google.com) and my browser was able to display the same test phrases in English and Chinese fine, so I’m guessing it’s not that.

    Thanks for any help,

    Michael

  7. Its simple ab! Because we can write one. Just as we can write ‘one more’ php framework, or ‘one more’ JavaScript library, when there are already so many available.

  8. hello,

    I tried this but it doesnot translate anything and does not print error as well. I tried ..

    require_once(‘googleTranslate.class.php’);

    $gt = new GoogleTranslateWrapper();

    /* Translate tedt from one language to another */
    $test = “Good Night”;
    echo $gt->translate($test, “en”, “de”);

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

    No error And print Good night .. Means Translation ..

    Wants to help

    Hridaya

  9. Well Hridaya, Google translates ‘Good Night’ in English to ‘Good Night’ in German, you can check with the online Google Translation service. Incidentally the second parameter to the ‘translate’ method should be the destination language: So your above code should be:

    $gt->translate($test, “de”, “en”);

    to translate English to German

  10. Thanks for the script Sameer, it works like a charm!!

    I use it to translate parts of my blog from Dutch into English. The script is on a separate page and I “pull” it in using AJAX so the page won’t reload.

    I’m not an expert but installing was a piece of cake.

  11. Great Sameer! I’m using this on my site now. It’s working perfect.

    Can i just ask…

    Does this class provide google with a “valid and accurate http referer header”… as requested in the terms?

    Googles terms are so damn hard to understand!

    Also, Do you think you could add a function like “getBranding()”, to call the “google.language.getBranding(opt_element, opt_options)” javascript call???

    Thanks again for this great script!

    Cheers.

  12. Hello Bork!

    Currently the class sends a blank ‘Referrer’ header. Edit the following lines in the ‘googleTranslate.class.php’ file:

    change :

    curl_setopt($ch, CURLOPT_REFERER, $this->_siteUrl);

    to :

    curl_setopt($ch, CURLOPT_REFERER, “http://www.xyz.com”);

    Where ‘xyz.com’ is your site name.

    There will be a total of 2 such lines.

  13. Hi.
    I know my question is stupid, but I can’t make this class work.
    When I run example.php I get this :

    translate($test, “en”, “fr”)); /* 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)); ?>

    I know it’s something with including this class or with my php or something else.
    The thing is the script stops at

    echo($gt->translate($test, “en”, “fr”));

    It seems it can’t recognize the method.
    Help me please

  14. I don’t know why, but the test doesn’t pass. I always get ‘Test failed’. Any ideas? Maybe google service doesn’t work?

  15. Hi Sameer, is it possible to translate a whole page with this wrapper please ?
    Because If I want to translate some more text I need to define every – one by one. Thanks

  16. Hi,
    i have created my own version of this class for the company that i work for, and i am sending the entire output buffer contents to the API for translation,

    however it is translating Javascript code aswell from English to the language which i have chosen.
    Does anybody know how to stop this from happening?

    Thanks

  17. Hi!

    I wrote a script to translate in english a text written in any language the user wants. I just want to know if there is no way to do it more efficient.

    here’s:

    header(“Content-type: text/html; charset=utf-8”);
    require_once(‘googleTranslate.class.php’);

    $gt = new GoogleTranslateWrapper();
    $test = “Bonjour de cette partie du monde”; /* text in any language… */
    $Lang = $gt->getDetectedSource(); /* language detection */
    echo $gt->translate($test, “en”, “$Lang”);

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

  18. You can do something like this:

    $gt = new GoogleTranslateWrapper();

    /* Translate text from one language to another */
    $test = ‘hello’;

    /* language detection */
    $lang = $gt->detectLanguage($test);
    echo $gt->translate($test, “fr”, $lang[‘language’]);

  19. I converted my text from english to france.Now My site shows in french.Now i want to convert it from French to Arabic then Arabic to English. What I Mean how I can chnage source and destination dynamicly and how I can tell to google?

  20. Hey sameer,

    thx alot for the script. It was of great help for me.

    However my site response has gone very slow after i translated it.

    Can you please tell me some way to speed up the translation process?

    Regards

  21. If the content you need to translate does not change frequently then you can cache the translated result and use it the next time the same content is requested for translation. This will require a bit of extra programming. Other then that there is nothing you can do much.

  22. Hey Sameer Thx for the reply,

    One more thing,

    I want to translate english to chinese (en to cn)
    but its giving invalid translation pair.

    Can you please tell me a way around?

  23. You need to use ‘zh-CN’ and not ‘ch’ for simplified Chinese. Make sure you add the following line at the start of your php file, or you will see gibberish characters.

    header(“Content-type: text/html; charset=utf-8”);

  24. Dear Sameer,

    I must say hats off to you. Wonder full script, and amazing use of curl. I was looking this type of solution from last few month but all were paid or it takes me to google page from where it display add at top.

    Wonderful man have a look of your work http://ekomkaar.com I use this in my project, and credit goes to you.

    thanks Man, whenever you need java help do call me I will definitely help you. contact me at info@ekomkaar.com

  25. Sameer – i am still using your script – it really is amazing – and great of you to release it with a fee.

    You say in one of your comments above – that it can translate whole pages. Does your script allow for the maximum 5000chr length of the translate (by breaking the page apart?), or will it result in a untranslated page.

    Many thanks

  26. I’ve enabled cURL and tried to run the test. Yet, it still prints ‘Test Failed’
    onscreen.Can anybody tell me some way solve the problem?

Comments are closed.