01
Jan

Google Translate API – GTranslate PHP Library

Just finished a PHP Library that implements Google Translate API.

 

How it works ?

The Library allows you to translate any phrase from one original language to another.

Usage

GTranslate library allows you to translate any language to another, the usage is fairly simple.

  1. You just need to require the library
    1. require(“GTranslate.php”);
  2. Instantiate the GTranslate Object
    1. $gt = new Gtranslate;
  3. Request for a translation
    1. $gt->it_to_en(“Ciao mondo”);

How to

You can call the translation with any country you want, altough there are an available list of translatable coutries, on the languages.ini file. You can tanslate using the abreviation of the country or the full name.

$gt->english_to_german(“Hello”);

or

$gt->en_to_de(“Hello”);

Wil give you the same result.

Download

You can download the GTranslate PHP library at Google Code Page

http://code.google.com/p/gtranslate-api-php/

Example

require("GTranslate.php");
 try{
   $gt = new Gtranslate;
    echo "Translating [Hello World] from English to German =>".$gt->english_to_german("hello world")."";
    echo "Translating [Ciao mondo] Italian to English => ".$gt->it_to_en("Ciao mondo")."";
 
 } catch (GTranslateException $ge) {
    echo $ge->getMessage();
 }

Related posts:

  1. Zend Framework: How-to interact with Google Calendar (Part 1/2)
  2. Google Apps Next Language War – Ruby, Perl, Java and Php on the lead

enjoyed this post? share with others:

twitter stumble upon digg

This entry was posted on Thursday, January 1st, 2009 at 12:33 am and is filed under Random Thoughts. You can follow any responses to this entry through the RSS 2.0 feed.

comments

20
  1. January 1st, 1970 | Hakima says:

    Dear Mr Da Silva

    I am a student from Moroccco.
    I wanted to thank you very much for providing us with teh Google translate API. I am working on an application that needs to use Google’s translation services and I needed the API in PHP.
    So thank you very much!

  2. January 1st, 1970 | josedasilva says:

    You’re welcome Hakima ,

    I hope that the API helps you to achieve your goals. Any doubts feel free to contact me.

  3. May 18th, 2009 | Gilberto Albino says:

    Olá José.
    Eu utilizei sua classe, mas estive vendo que o processo limita a quantidade de texto por que é enviado via GET.
    teria alguma forma de driblar isto?

  4. June 6th, 2009 | josedasilva says:

    Olá Gilberto

    Infelizmente a documentação do Google apenas disponibiliza passagem de parametros usando o protocolo GET, e aí terá sempre o problema dos caracteres. A única forma que vejo como possível de passar ao lado do limite, é jogar as regras do jogo.

    No texto que deseja traduzir, separe o texto em N textos, talvez partindo a string por frases e efectue vários pedido à API de tradução.

    Espero ter ajudado

  5. June 13th, 2009 | Gilberto Albino says:

    Sim, eu fiz um esquema interessante em ajax José!
    Bem simples! Eu coloquei uma classe CSS nas partes que desejo traduzir. E está funcionando perfeitamente.
    De qualquer forma, me desculpe por não ter lhe agradecido por ter disponibilizado sua classe.

  6. July 15th, 2009 | Alejandro says:

    Hi, sorry about the comment from above.
    Tfirst, tnx for you software it works.
    Unfortunately Im getting something like this from my ES to CS translation:"Tyto otázky dnes musím udělat s vámi, osobnost, charakter, fyzickou část. Impulsivity iniciativ. Je čas na změnu duchovní. Časté příčiny movilizarn vás."
    I got charset=iso-8859-1 and it should wok but it doesnt, also happens with chinese, I also added: <html dir="ltr" lang="cs" xmlns="http://www.w3.org/1999/xhtml">

    Do you have any clue why is this happening?
    Tnx!!

  7. July 17th, 2009 | josedasilva says:

    Hello,

    Thank you for your kind words about the class. About your issue, i am seeing this as a encoding issue, the issue that i am seeing is that you are using ISO instead of UTF-8 on the message sent to the class.

    Try to make a utf8_encode()/decode() on the string. Let me know if it worked out!

  8. July 25th, 2009 | Forexheast says:

    what an informative posts, I will bookmark this site to digg. Regards, Reader.

  9. August 10th, 2009 | Bogdan says:

    Hi, thanks for this API. It works and it`s a time saving to see this API here.

  10. August 18th, 2009 | Miguel Melo says:

    Boas noites,

    Grande classe José! :)
    Um pequeno pormenor … estava aqui a testá-la e ela não me traduz palavras com acentos (por ex. maçã), alguma sugestão??
    Cumps

  11. August 19th, 2009 | josedasilva says:

    Olá Miguel,

    Efectuei um teste com a seguinte string:

    "o antónio que também é conceição comeu a maçã no reino da rússia" e a resposta da tradução de português para inglês foi "Anthony is also the Conception ate the apple in the realm of russia".

    A classe parece ter funcionado bem, ou está a traduzir para uma outra língua que não inglês?

    De qualquer forma, verifique qual o encoding da string que está a passar para tradução, o problema pode estar relacionado com isso.

  12. August 25th, 2009 | Chris says:

    Excellent, apart from one thing! How do i see the tranlated text into a variable; it does seem to return any value?

  13. September 15th, 2009 | Claudio says:

    Olá from Brasil ! Excelent post !

  14. September 19th, 2009 | João Chagas says:

    Olá José, achei este trabalho espectacular e tem facilitado em muito a minha vida. No entanto tenho uma duvida que poderá ser interessante para toda a gente que se interessa pelo google translate, que é quando não queremos que uma palavra seja traduzida.
    Ora vejamos, em Portugal existe uma praia que se chama "praia da consolação", se traduzir de PT para Inglês obtenho o seguinte resultado óbvio: "Consolation Beach", mas a finalidade é que a tradução fosse "Consolação Beach".
    Será que existe alguma forma de colocar algum caractere especial na palavra que não queremos que traduza?

    De qualquer forma muito obrigado pelo seu trabalho.

    João Chagas

  15. September 29th, 2009 | Andres says:

    Please Help…

    I would like to use this library but I’m must be doing something wrong.

    OI get a printout of every url call to the service and then the page shows up but the values on the table are the english ones, what am I doing wrong?

    Thanks in advance!

  16. September 29th, 2009 | Andres says:

    The code did not show up in the previous post, had to remove the php open/close tags:

    // lang is early array defined as $lang['foo'] = "this is english";

    require("../GTranslate.php");

    $gt = new Gtranslate;

    foreach($lang as $key => $value) {
    try {
    $gt->english_to_spanish($value);
    } catch (GTranslateException $ge) {
    $lang[$key] = $ge->getMessage();
    }
    }

    unset($value);

  17. October 5th, 2009 | Rimoka says:

    Tghis is error? You can help me fix it? pl PM to my email, thanks
    http://truongthehoa.com/translate/index.php

  18. October 19th, 2009 | Richard says:

    gTranslate most used Add-on.

    simple and fast.

    Video about time for installation and translation.

    http://www.youtube.com/watch?v=gGB2Wecu-CE

  19. October 22nd, 2009 | josedasilva says:

    Hi Richard

    Thank you for the suggestion.

  20. November 11th, 2009 | Peter says:

    Hi Jose Dasilva,

    I’ve been tryin’ to implement your code, but since I couldn’t make it work on my server, I decided to simply try your example, and even that won’t work.

    Does the web server has to be configured in any way to make it work?

    Any settings that should be made etc?

    Hope you have time for a quick answer. I have downloaded and up loaded:

    example.php
    GTranslate.php

    on http://www.buchardt.it/test/example.php

    Thanks,

    Peter

  21. November 17th, 2009 | Julien says:

    Hi Jose,

    thanks for this nice work :)

    Is there any limit in terms of the text size? I have an error on line 179 with long texts.

    Any idea?

    Thanks, Julien

  22. November 17th, 2009 | Julien says:

    I’ve updated to the latest version, I now have an error at line 192

  23. November 18th, 2009 | josedasilva says:

    What the error says ?

  24. November 26th, 2009 | casas en castelldefels says:

    This code can only be used locally but not online.
    any idea

  25. January 19th, 2010 | ageent says:

    Hi all. Using Gtranlate and Simplehtmldom I wrote a class for easy translate of the entire site into other languages. Here’s a link to the draft http://code.google.com/p/globaltranslate please evaluate my work ) Jose da Silva thanks for Gtranlate

  26. February 12th, 2010 | josedasilva says:

    Hi

    It’s true, although is not a code problem, google translate api only supports translations until 5000 characters.

    You can use for bigger texts, but you have to be creative, splitting the text into chunks and making several calls.

  27. May 10th, 2010 | Anil Kumar Panigrahi says:

    Hi,

    I am Anil Kumar Panigrahi , translate API is very good, thank you for sharing. I have small doubt in that.

    When i have text in english it is easily converted in to french. But converted french data to english it is converted. I never got the exact text.

    eg: Google’s translation API – ( in English, original text )

    Google API de traduction – ( in French Converted English into french)

    Google Translation API – ( in English Converted French into English)

    Please suggest me.

  28. May 12th, 2010 | josedasilva says:

    Hello Anil

    Thank you for the comment. About you doubt, there are many cases were you will not get the expected result, meaning, the exact original data, that’s mainly because of some specific language glitches.

    That’s why computer translation is not the same as human translation.

    What were you trying to perform with this ? Just a curiosity or other?

    Jose

  29. September 17th, 2010 | Samet ARAS says:

    Hello,

    Not been translated in more than 1500 characters. How to fix?

    Regards,
    Samet ARAS.

  30. January 22nd, 2011 | Joern says:

    Hello Mr. da Silva,

    are there any issues with the GTranslate right at the moment? If i use the examples given i have no success. I tried everything also with API-Key. I wonder what the functions setUserIp & setHTTPReferrer are for? Is this necessary? Did i overread something? As i said i use your sample script with API-Key and i get the error: Unable to perform Translation:invalid translation language pair.

    I would love to use your script on my page, because it looks very lean and clean. I’m looking forward for a Tipp which can help me going on with my project. Thanks a lot for your effort!

    Best Wishes!
    Joern

  31. January 22nd, 2011 | josedasilva says:

    Hello Joern

    Thank you for the feedback, I juts released a new version of the library, there were some issues with the languages.v2.ini file, maybe this was making some languages not work. Can you please try now ?

    Let me know if i can help you on anything more.

    Thank you
    Jose

  32. January 24th, 2011 | Joern says:

    Hello Jose,

    thanks for you swift feedback. I installed the new version, but unfortunately the result is exactly the same. I removed the bugs from the language file already after reading the project page. But actually i don’t think your code causes the problems. Maybe some parameters are incorrect. Could you publish an example of code which makes use of the paramers like ip and referrer? Are those mandatory?

    Thanks for your help again.
    Joern

  33. January 25th, 2011 | Joern says:

    Hello Jose,
    the problem is indeed the languagefile v2. All the values ar in ” like ‘en’ and so they are in the array. if the program is checking the array for the languages it will compare en with ‘en’, which leads into a FALSE. I think thats it.

    Best Wishes
    Happy Joern ;-)

  34. January 31st, 2011 | Ali says:

    Hi,

    Does you class take care of 5000 chars limit imposed by Google? For e.g. if I send 55240 characters to your class, will it automatically divide it into sections of 5000 chars and send to Google for translation?

    Thanks

  35. February 4th, 2011 | DIEGO says:

    Olá, José. Testando o seu código com uma string, ele funciona bem.

    Mas o meu objetivo tem sido pegar notícias de um site externo (fiz isso com sucesso) e convertê-la de Português para Inglês. E neste caso está ocorrendo problemas com a acentuação.

    Tentei mudar o encoding e não deu certo. Já verifiquei o encoding do site externo e deixei igual aqui e não deu.

    Tem alguma dica para isso?

    Abraço!

  36. February 7th, 2011 | DIEGO says:

    Resolvido o problema com acentuação.

    Basta usar a função utf8_encode.

    Ex:
    $string = “Maçã é uma delícia.”
    echo $gt->portuguese_to_english(utf8_encode($string));

  37. April 4th, 2011 | steve says:

    Can we hire you to integrate the Google Translate API into our site. My understanding is that it will allow us to translate the entire site from English to Spanish.

    Thanks in advanced

  38. April 13th, 2011 | josedasilva says:

    Hello Steve

    Just drop me an email so that we can start discussing your needs.

    Thank you
    Jose da Silva

  39. May 5th, 2011 | Sebastian says:

    Hi Jose,
    I have GTranslate widget on my website, ,
    Sebastianand the default language is English as many articles are in english, and so is my target audience.
    Some of my columnists will write in spanish, but I don’t get English as a translation option on the dropdown (although I chose as one of the options).
    Do you know a way around this?
    Appreciate your help if possible!
    regards ,
    Sebastian

  40. June 29th, 2011 | Charl says:

    Thank you for this script, I was wondering if there is a way to let google auto detect the language with our API? I have 5000 products descriptions to translate and I have no idea in which language they are and they are all in different languages

  41. September 3rd, 2011 | Axonefqy says:

    Would you like a receipt? nymphets young bbs hyo

  42. September 5th, 2011 | Iyapgxny says:

    A pension scheme pthc gold %P

  43. September 22nd, 2011 | Bvxdxfjg says:

    The United States Pedo Comics 8080

  44. September 23rd, 2011 | Rsvxpbme says:

    I was born in Australia but grew up in England Loltia Dark Girl Toplist Models =(((

  45. September 24th, 2011 | Jnczwknc says:

    Will I get travelling expenses? Hooters Teen Models
    32149

  46. September 26th, 2011 | Jacob Winski says:

    GTranslate will no longer work.

    Google Translation API v1 (which GTranslate uses) is depricated and will be fully shut off at the end of 2011. Google no longer offers free translation service. v2 of the API is paid only.

    Source: http://code.google.com/apis/language/

    For a free service, the only option seems to be Microsoft (Bing) Translator.

leave a comment

Trackbacks

1