3

I am trying to use the google translation API as shown on this page...

https://developers.google.com/translate/v2/using_rest

When I replace my API key, it works correctly and display the translated text as shown below.

GET https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&target=de&q=Hello%20world

{
    "data": {
        "translations": [
            {
                "translatedText": "Hallo Welt",
                "detectedSourceLanguage": "en"
            }
        ]
    }
}

I will like to return only the text i.e. "Hallo Welt" using PHP.

I used json_decode function, but it returns everything.

1
  • What's your PHP Code? Commented Mar 24, 2013 at 6:20

2 Answers 2

6
$url = "https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&target=de&q=Hello%20world";
$data = file_get_contents($url);
$json = json_decode($data);

echo $json->data->translations[0]->translatedText;
Sign up to request clarification or add additional context in comments.

2 Comments

This does not return anything. But print_r($json->data->translations); returns Array ( [0] => stdClass Object ( [translatedText] => Hallo [detectedSourceLanguage] => en ) )
Edited the answer, translations is an array.
0
$object = json_decode($yourJSONString);
echo $object->data->translations->translatedText;

Once you have used json_decode(), you just use the resulting object however you use any other PHP object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.