translate a PHP $string using google translator API

Posted by Toni Michel Caubet on Stack Overflow See other posts from Stack Overflow or by Toni Michel Caubet
Published on 2011-01-09T16:52:20Z Indexed on 2011/01/09 17:54 UTC
Read the original article Hit count: 263

Filed under:
|

hey there!

been google'ing for a while how is the best way to translate with google translator in PHP, found very different ways converting URLS, or using Js but i want to do it only with php (or with a very simple solution JS/JQUery)

example:

//hopefully with $from_lan and $to_lan being like 'en','de', .. or similar
function translate($from_lan, $to_lan, $text){

// do

return $translated_text;

}

can you give me a clue? or maybe you already have this function..

my intention it's to use it only for the languages i have not already defined (or keys i haven't defined), that's why i wan it so simple, will be only temporal..

EDIT

thanks for your replies we are now trying this soulutions:

function auto_translate($from_lan, $to_lan, $text){
// do


$json = json_decode(file_get_contents('https://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=' . urlencode($text) . '&langpair=' . $from_lan . '|' . $to_lan));
$translated_text = $json->responseData->translatedText;


return $translated_text;

}

(there was a extra 'g' on variables for lang... anyway)

it returns: works now :)

i don't really understand much the function, so any idea why is not acepting the object? (now i do)

OR:

unction auto_translate($from_lan, $to_lan, $text){
// do

// $json = json_decode(file_get_contents('https://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=' . urlencode($text) . '&langpair=' . $from_lan . '|' . $to_lan)); // $translated_text = $json['responseData']['translatedText']; error_reporting(1); require_once('GTranslate.php'); try{ $gt = new Gtranslate(); $translated_text = $gt->english_to_german($text);

 } catch (GTranslateException $ge)
 {
       $translated_text= $ge->getMessage();
 }


return $translated_text;

}

And this one looks great but it doesn't even gives me an error, the page won't load (error_report(1) :S)

thanks in advance!

© Stack Overflow or respective owner

Related posts about php

Related posts about google-translate