0

I am trying to get translated text from Google Translate REST API in PHP. Response is in JSON format and it looks like this:

{
  "data": {
    "translations": [
      {
        "translatedText": "translated text which I want to get",
        "detectedSourceLanguage": "en"
      }
    ]
  }
}

I wonder how can I extract it as a PHP variable? My current code is that but it is not working:

$ownwords = $mysqli->real_escape_string($_GET['ownwords']);

$geoownwordsapiurl = "https://translation.googleapis.com/language/translate/v2?key=SOMEVALIDAPIKEY&q={$ownwords}&target=en";

$geoownwords = json_decode(file_get_contents($geoownwordsapiurl), true);

foreach ($geoownwords as $geoownword) {
    $translatedwords = $geoownword['data']['translations']['translatedText'];
}

echo $translatedwords;
8
  • what do you mean by "it does not work" ? do you get an error ? wrong result ? no result ? Commented May 29, 2018 at 19:05
  • @ᴄʀᴏᴢᴇᴛ not a single error. When I run a test PHP file it is blank Commented May 29, 2018 at 19:07
  • 1
    Skip the foreach. You foreach an array but still use direct path. Commented May 29, 2018 at 19:08
  • @Andreas So how can I skip foreach? Commented May 29, 2018 at 19:11
  • Just delete the line starting with foreach, and the line }. Then replace geoownword with geoownwords Commented May 29, 2018 at 19:12

1 Answer 1

1

Not sure what you want to do in the loop (I just build a string of all of them below), but you need to loop translations, assuming there can be more than one:

$translatedwords = '';

foreach($geoownwords['data']['translations'] as $geoownword) {
    $translatedwords .= $geoownword['translatedText'];
}
echo $translatedwords;

If there will be only one:

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

1 Comment

Now echo is "Array" and nothing more. Just Array

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.