FlamingGenius
FlamingGenius

Reputation: 216

Google Translate returns weird string?

So I am trying to get a string back from google but translated as you can see

function Translate($fromLang,$toLang,$text){
        $texts = file_get_contents(
        "https://translate.googleapis.com/translate_a/single?client=gtx&sl="
        . $fromLang .
        "&tl=" . 
        $toLang . "&dt=t&q=" . $text);

        return $texts;
    }

But this returns an ugly string like this if the parameters are set to

Print(Translate("en","es","Hello"));

[[["Hola","Hello",null,null,1]],null,"en"]

According to the "scattered" and poor documentation on personal use without paying the enterprise fees this should work

Upvotes: 0

Views: 350

Answers (1)

chris85
chris85

Reputation: 23892

You need to use json_decode and then return the third level of the array.

function Translate($fromLang,$toLang,$text){
    $texts = file_get_contents("https://translate.googleapis.com/translate_a/single?client=gtx&sl=" . $fromLang . "&tl=" .  $toLang . "&dt=t&q=" . $text);
    $array = json_decode($texts, TRUE);
    return $array[0][0][0];
}

The returned JSON is two levels in, and the translated value is the first value of that. So you need [0][0] to get to the right level, and then [0] to get the value.

If you are unsure what to access you can always use print_r in the Translate function on the $array value to see what it contains.

Upvotes: 3

Related Questions