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

如何修复无法正常运行的DeepL cURL PHP翻译代码?

解决DeepL翻译API返回空字符串的问题

问题根源分析

你的代码存在三个关键错误,导致API返回空响应:

  1. 认证头拼接错误
    原代码中Authorization头的写法错误,双引号内的. $authKey会被当作字符串的一部分,导致认证密钥无法正确传入服务器,触发无提示的认证失败。
  2. 请求内容类型不匹配
    代码设置了Content-Type: application/json,但POST数据采用的是application/x-www-form-urlencoded格式(键值对用&拼接),服务器无法解析请求,直接返回空响应。
  3. 缺少HTTP状态码检查
    仅检查cURL底层错误不足以排查问题,当HTTP请求返回4xx/5xx状态码(如认证失败、参数错误)时,curl_exec()会返回空字符串,此时需要通过HTTP状态码定位问题。

修正后的代码

<?php
$text = 'Hi there';
$source_lang = "en";
$target_lang = "de";
$tag_handling = "xml";
$ignore_tags = "x";
$formality = "";
$url = "https://api.deepl.com/v2/translate";
$authKey = "your-auth-key-here";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

// 修正认证头,正确传入密钥
$headers = array(
    "Authorization: DeepL-Auth-Key $authKey",
    "Content-Type: application/x-www-form-urlencoded", // 匹配表单格式
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

// 使用http_build_query构建标准表单数据,自动处理编码
$data = http_build_query(array(
    'text' => $text,
    'source_lang' => $source_lang,
    'target_lang' => $target_lang,
    'tag_handling' => $tag_handling,
    'ignore_tags' => $ignore_tags,
    'formality' => $formality
));

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

// 调试完成后建议开启SSL验证,避免安全风险
// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$resp = curl_exec($curl);

// 检查cURL底层错误
if ($errno = curl_errno($curl)) {
    $error_message = curl_strerror($errno);
    echo "cURL error ({$errno}):\n {$error_message}";
} else {
    // 获取HTTP状态码,排查服务器端错误
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    if ($httpCode !== 200) {
        echo "HTTP Error: {$httpCode}\n";
        var_dump($resp); // 打印服务器返回的错误详情
    } else {
        var_dump($resp);
    }
}

curl_close($curl);
?>

额外注意事项

  • 调试完成后请移除CURLOPT_SSL_VERIFYHOST和CURLOPT_SSL_VERIFYPEER的禁用设置,保障请求安全性。
  • 若不需要某个参数(如formality为空),可直接从$data数组中移除,减少无效参数传递。
  • 确保你的DeepL认证密钥有效且有足够的调用额度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 21:07:41