Skip to content

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();
 }
Published inRandom Thoughts

52 Comments

  1. 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. You’re welcome Hakima ,

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

  3. 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. 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. 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. 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"&gt;

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

  7. 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. what an informative posts, I will bookmark this site to digg. Regards, Reader.

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

  10. Miguel Melo Miguel Melo

    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. 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. Excellent, apart from one thing! How do i see the tranlated text into a variable; it does seem to return any value?

  13. Claudio Claudio

    Olá from Brasil ! Excelent post !

  14. 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. Andres Andres

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

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

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

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

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

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

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

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

  24. Hello,

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

    Regards,
    Samet ARAS.

  25. Joern Joern

    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

    • 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

  26. Joern Joern

    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

  27. Joern Joern

    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 😉

  28. Ali Ali

    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

  29. DIEGO DIEGO

    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!

  30. DIEGO DIEGO

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

  31. steve steve

    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

    • Hello Steve

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

      Thank you
      Jose da Silva

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

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

  34. Jacob Winski Jacob Winski

    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.

  35. That is really fascinating, You are a very skilled blogger. I’ve joined your feed and look ahead to looking for extra of your magnificent post. Additionally, I’ve shared your website in my social networks

  36. mon mon

    doesn’t work..

  37. winboy winboy

    Hi,

    I have installed the gtranslate.api and run the example.php program..

    I have faced the error in “Unable to perform Translation:Suspected Terms of Service Abuse. Please see http://code.google.com/apis/errors

  38. He died in 1985 but this very personal museum is really a lasting reminder of
    the very remarkable man. A very convenient approach to search for things on the web is to only speak your pursuit term.
    We’ll start our tour at Marina Grande on the north shore of the island, about one third from the way in from the easternmost point.

  39. A law firm http://connect.masslive.com/user/kiebyjitejal/index.html lolita hard porn pics
    pretty much everyone who thinks this is pee has never been able to pleasure a girl right, when one stimulates the gspot, fluid builds up (that isnt pee, its similar to prostate fluid) and when she orgasms its ejected through her pee hole, so even though its going through the same hole, it isnt pee

  40. It’s amazing to pay a visit this web site and reading the views of all friends about this
    article, while I am also zealous of getting
    familiarity.

  41. siva siva

    its not working

  42. Much is considered and written about the crimes committed through the aborigines from the white man,
    however it has to be remembered that the blacks got great provocation.
    His fee was 110 guineas, which in the hotelkeeper
    was 30 guineas. Much maudlin sentimentally, and empty declaration,
    are already written and talked about crime, and contrary to
    the punishment of criminals with death.

  43. Spot on with this write-up, I really feel this site needs
    far more attention. I’ll probably be returning
    to see more, thanks for the info!

    Check out my web-site: web development

Leave a Reply to Rimoka Cancel reply

Your email address will not be published. Required fields are marked *