从谷歌翻译API获取翻译作为PHP变量



我正在尝试从PHP中的Google Translate REST API获取翻译文本。响应采用 JSON 格式,如下所示:

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

我想知道如何将其提取为 PHP 变量?我当前的代码是这样的,但它不起作用:

$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;

不确定你想在循环中做什么(我只是在下面构建一个字符串(,但你需要循环translations,假设可以有多个:

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

如果只有一个:

echo $geoownwords['data']['translations'][0]['translatedText'];

最新更新