我正在尝试使用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;
答案 0 :(得分:1)
不确定你想在循环中做什么(我只是在下面构建一个包含所有这些字符串的字符串),但你需要循环translations
,假设可以有多个:
$translatedwords = '';
foreach($geoownwords['data']['translations'] as $geoownword) {
$translatedwords .= $geoownword['translatedText'];
}
echo $translatedwords;
如果只有一个:
echo $geoownwords['data']['translations'][0]['translatedText'];