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

This site is a digital habitat of Sameer Borate, a freelance web developer working in PHP, MySQL and WordPress. I also provide web scraping services, website design and development and integration of various Open Source API's. Contact me at metapix[at]gmail.com for any new project requirements and price quotes.

63 Responses

1

Parcye

March 3rd, 2010 at 12:58 am

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

Kykyryzo

March 3rd, 2010 at 6:30 am

Fhank you. just what I need)) sorry for my english

3

Md Sajjadul Farooque Robin

March 3rd, 2010 at 7:47 am

Nice Handy Work!

Thanks

4

nancy

March 5th, 2010 at 8:40 pm

thanks very much ! first tools

5

Saar

March 9th, 2010 at 2:28 pm

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?

sameer

March 10th, 2010 at 5:47 am

Google strips any newline characters form the text. Although it does accept it with the online translation service.

7

PHP: Wrapper para google translate | The Epsilon Crew

March 11th, 2010 at 1:27 am

[...] en: Code-Diesel. Desarrollo, Google, [...]

8

Manuj

March 14th, 2010 at 7:36 pm

Thanks for the great tool! I was able to integrate translation in my php script within minutes!

9

Guari

March 24th, 2010 at 4:22 am

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

10

MadHD

March 25th, 2010 at 8:12 am

Very good script! Thanks very much.

11

Stephen

April 5th, 2010 at 7:44 am

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!

sameer

April 6th, 2010 at 12:16 am

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

13

Bjorn

April 8th, 2010 at 6:58 am

Thanks a million Sameer. This is fantastic!

14

chinaNews

April 12th, 2010 at 10:35 pm

Thank u for you job.
And it’s very helpful to me.Very good script!

15

Michael

April 13th, 2010 at 6:45 am

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

sameer

April 13th, 2010 at 7:21 am

Hello Michael!

Add the following line at the start of your php code:

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

17

Michael

April 13th, 2010 at 8:31 am

Sameer:

Yep, that did it. Hehe. Thanks so much!

18

ab

April 18th, 2010 at 6:27 am

Why write another wrapper when there was already one available?

sameer

April 18th, 2010 at 9:39 pm

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.

20

richa

April 20th, 2010 at 1:55 am

hii sameer,
can u plz snd me easiest code for pagination….
m newbie here

sameer

April 20th, 2010 at 1:58 am

22

Hridaya Ghimire

April 20th, 2010 at 11:39 am

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

sameer

April 20th, 2010 at 9:34 pm

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

24

Aiko

April 23rd, 2010 at 2:17 pm

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.

25

blogshit

April 26th, 2010 at 9:07 pm

thanks mate, now i can translate what they search on my blog into english :P

26

Bork

April 29th, 2010 at 12:51 am

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.

sameer

April 29th, 2010 at 3:46 am

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.

28

Dummy

April 29th, 2010 at 11:45 am

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

29

Dummy

April 29th, 2010 at 11:46 am

Sorry, I forget
I use
Apache Version : 2.2.11
PHP Version : 5.3.0

30

Dummy

April 29th, 2010 at 12:16 pm

Ok, I found the error. Delete these comments, please. It’s stupid :(

31

Dummy

April 29th, 2010 at 12:28 pm

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

32

Dummy

April 29th, 2010 at 12:53 pm

Test fails because the header is empty while I’m trying to make POST from local server ?

33

Artyom

April 30th, 2010 at 2:21 am

Thank you very much! I’ve faced the problems with cURL. And your class helped me a lot !

34

JK

April 30th, 2010 at 6:26 am

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

35

Matt

April 30th, 2010 at 7:21 am

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

sameer

April 30th, 2010 at 7:53 am

Yes JK!

You can translate a whole page with the class.

37

GoTcH

May 7th, 2010 at 2:14 am

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();

sameer

May 7th, 2010 at 6:40 am

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']);

39

çeviri

May 8th, 2010 at 1:30 pm

I think a lot of free online translation tools would have problems with this sort of linguistic problem.

40

atc

May 17th, 2010 at 1:32 am

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?

41

Anonymous Emailer

May 19th, 2010 at 12:03 am

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

sameer

May 19th, 2010 at 8:42 pm

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.

43

tony

May 20th, 2010 at 8:53 am

How would I go about using this class to translate the content of an entire page?

44

anonymous emailer

May 20th, 2010 at 11:44 pm

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?

sameer

May 21st, 2010 at 8:22 am

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″);

46

Chetan

June 10th, 2010 at 3:46 am

thnk u so much…………………

47

Manjit Singh

June 20th, 2010 at 2:20 pm

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

48

Bork

June 23rd, 2010 at 2:31 am

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

sameer

June 23rd, 2010 at 5:36 am

Bork, I’ve updated the library to support translation of text of more than 5000 characters.

50

jkc

June 24th, 2010 at 11:08 pm

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?

sameer

June 24th, 2010 at 11:29 pm

Try getting the exact error by using the following after the selfTest():

echo $gt->getLastError();

52

jkc

June 24th, 2010 at 11:46 pm

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

53

Fazer Site

June 29th, 2010 at 12:11 pm

Interesting this article.

54

asad

June 30th, 2010 at 2:51 am

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

55

Blutarsky

July 7th, 2010 at 6:02 am

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?

sameer

July 7th, 2010 at 7:42 am

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.

57

diya

July 15th, 2010 at 12:46 am

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

58

web designer

July 20th, 2010 at 2:34 am

Cool pure php code. I`w use it. Congratulations for the efforts

59

metalinspired

July 22nd, 2010 at 5:48 am

Great. Thank you.

60

RalphF

July 23rd, 2010 at 3:21 pm

What are the language options?

en is english
fr is french

how about spanish?
other languages?

Thanks

61

Aiko

July 25th, 2010 at 12:56 pm

Sameer you are my hero !!
No more 5000 character limit. Updated without a problem and again it works like a charm.

I wore a blog post about it: http://blog.atgp.nl/index.php?id=82

Thanks again!

sameer

July 25th, 2010 at 9:06 pm

Hello Ralph!
I’ve added a list of language codes at the end of this blog post above.

63

Jon

July 29th, 2010 at 3:15 pm

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 disabled for this post, but if you have spotted an error, feel free to contact me.

Sign up for fresh content in your email