简体   繁体   中英

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM