translate a PHP $string using google translator API

Toni Michel Caubet picture Toni Michel Caubet · Jan 9, 2011 · Viewed 49.7k times · Source

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:

    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'];
    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!

Answer

Savetheinternet picture Savetheinternet · Jan 9, 2011

I haven't tested this yet, but try:

function translate($from_lan, $to_lan, $text){
    $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;
}

EDIT: Fixed, tested and works.