DaftPlug
DaftPlug

Reputation: 60

Get translation from Google Translate API as PHP variable

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;

Upvotes: 0

Views: 576

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 79024

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

Upvotes: 1

Related Questions