You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中如何提取Google Translate API返回的翻译文本?

解决PHP提取Google Translate API翻译文本的问题

嘿,我来帮你搞定这个问题!先看看你的代码哪里出了问题,再给你修正后的方案。

首先,咱们先明确API返回的JSON结构:

{
  "data": {
    "translations": [
      {
        "translatedText": "你要获取的翻译文本",
        "detectedSourceLanguage": "en"
      }
    ]
  }
}

解码后得到的PHP数组结构是:

  • 顶层数组包含data键,对应一个子数组
  • data子数组里的translations键对应一个数组,里面的每个元素是一个包含翻译结果的子数组

你的代码问题所在

你用foreach ($geoownwords as $geoownword)遍历的是顶层数组(也就是包含data的那个数组),这时候每次循环的$geoownword其实是data对应的子数组,你再去访问$geoownword['data']自然就找不到这个键了,所以代码没法正常运行。

修正方案

方案1:直接访问(适合单次翻译的场景)

如果你的请求只翻译一段文本(就像当前的q={$ownwords}),那translations数组里只有一个元素,直接通过数组索引访问就行,不用循环:

$ownwords = $mysqli->real_escape_string($_GET['ownwords']);
// 对参数做URL编码,避免特殊字符导致请求错误
$encodedOwnwords = urlencode($ownwords);
$geoownwordsapiurl = "https://translation.googleapis.com/language/translate/v2?key=SOMEVALIDAPIKEY&q={$encodedOwnwords}&target=en";

// 先确保请求成功,避免后续报错
$response = file_get_contents($geoownwordsapiurl);
if (!$response) {
    die("无法连接到翻译API");
}

$geoownwords = json_decode($response, true);

// 直接提取翻译文本,增加存在性判断避免报错
if (isset($geoownwords['data']['translations'][0]['translatedText'])) {
    $translatedwords = $geoownwords['data']['translations'][0]['translatedText'];
    echo $translatedwords;
} else {
    echo "未能获取翻译结果";
}

方案2:循环遍历(适合批量翻译多段文本的场景)

如果你的请求里传递了多个q参数(比如批量翻译),那translations数组会有多个元素,这时候就需要遍历这个数组:

$ownwords = $mysqli->real_escape_string($_GET['ownwords']);
$encodedOwnwords = urlencode($ownwords);
$geoownwordsapiurl = "https://translation.googleapis.com/language/translate/v2?key=SOMEVALIDAPIKEY&q={$encodedOwnwords}&target=en";

$response = file_get_contents($geoownwordsapiurl);
if (!$response) {
    die("无法连接到翻译API");
}

$geoownwords = json_decode($response, true);

// 遍历translations数组,先判断数组是否存在
if (isset($geoownwords['data']['translations']) && is_array($geoownwords['data']['translations'])) {
    foreach ($geoownwords['data']['translations'] as $translation) {
        $translatedwords = $translation['translatedText'];
        echo $translatedwords . "<br>"; // 输出每一段翻译结果
    }
} else {
    echo "未能获取翻译结果";
}

额外提示

  • 对$ownwords做urlencode()处理很重要,不然如果参数里有空格、中文等特殊字符,会导致URL格式错误,API无法正常解析请求。
  • 加上存在性判断(isset())可以避免因API返回结构异常导致的PHP报错,让代码更健壮。

内容的提问来源于stack exchange,提问作者DaftPlug

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:00:31