Google Translate – PHP class for automatic translation

Edit: 06.03.2012: Unfortunately Google no longer provides free access to their Google Translate API so this class does not work any more. You can still use it as a learning reference on how to use Web APIs

Here is a very simple in use class to translate any text from one language to another using Google Translate service. The results are cached, so it is quite fast.
It supports all the languages which are available on translate.google.com.
Cache is stored in php files, so you do not need any database at all!

The usage is very simple:


include 'GoogleTranslate.php';
$t = new GoogleTranslate;
$t->inLang = 'en';
$t->outLang = 'de';
echo $t->translate('Hello World');

The above code will display “Hello World” in German.
Code is release under the MIT license, so you can use it even in commercial projects.
Enjoy and please leave a comment!

This entry was posted on Tuesday, January 19th, 2010 at 7:09 pm and is filed under PHP. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

9 Responses to “Google Translate – PHP class for automatic translation”

  1. jap Says:

    Thank you it work like a charm. And cache is a very good idea.

  2. Jane Duyan Says:

    Well if you are translating a few words then it will be fine, but if you are translating paragraphs using this tool, you will definitely not have good results. Translation tools do not really give good results.

  3. wisdom Says:

    It’s not working anymore
    please update

  4. admin Says:

    wisdom: Example file was indeed a bit incorrect, sorry. I updated it- works fine now.

  5. jamesjara Says:

    error.

  6. admin Says:

    I just checked the class and it does work. Something must be wrong with your server. Please tell me what error you have and maybe I can find a solution.

  7. Martin Says:

    I Just added auto-detect language to the class.

    http://pastebin.com/4vYLQCB5

    Changed: Line 13 + added function detect() and implemented detect() in the translate() function.

    Please take a look at it, it could be cool if you implement it in your code.

  8. Pixeler Says:

    Hello thank you for your hard work.
    I am having problems with chdir(__DIR__) you are using. I use many includes with many folders. If I comment them out, I have no problems with using your class, if I don’t it is screwing all my includes.

    Fast fix would be great or any solution for this problem.

  9. admin Says:

    To fix it do:
    1. comment out: chdir(__DIR__);
    2. change the path: private $cacheDir = ‘gt_cache/’;

    I added this “chdir” to make sure it will work out of the box. Of course it is not the best solution, but many beginners have problems setting include paths to their classes.

Leave a Reply

 
TopOfBlogs Web Development & Design Blogs