Jan 1 2009

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

52 comments on “Google Translate API – GTranslate PHP Library

  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. Pingback: Se- Di- Te- almost done! | The Walton Firm Memos: /**/

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

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

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

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

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

    Miguel Melo on said:
  8. 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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    steve on said:
  23. 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

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

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

    Jacob Winski on said:
  26. 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

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

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

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>