PHP 8.6批量调用Azure Translator时,把多条文本按固定顺序组成JSON数组,一次请求指定所需目标语言,再按输入位置和结果中的to字段建立映射。不要把所有译文压成一个字符串,否则多文本、多语言场景容易失去对应关系。
选择资源端点和认证方式
使用php 8.6 cli和curl扩展。下面的requestjson辅助函数保存为同目录的http.php;调用方从环境变量读取已获得相应权限的令牌,不把令牌写入源码。http错误由业务脚本检查,网络超时不会自动重发写请求。
<?php
function requestJson(string $method, string $url, array $headers = [], ?array $data = null): array {
$ch = curl_init($url);
$headers[] = 'Accept: application/json';
$options = [CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers, CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 45, CURLOPT_FOLLOWLOCATION => false,
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS];
if ($data !== null) {
$headers[] = 'Content-Type: application/json';
$options[CURLOPT_HTTPHEADER] = $headers;
$options[CURLOPT_POSTFIELDS] = json_encode($data, JSON_THROW_ON_ERROR);
}
curl_setopt_array($ch, $options);
$raw = curl_exec($ch);
if ($raw === false) { throw new RuntimeException('Network request failed'); }
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
return [$status, $raw === '' ? [] : json_decode($raw, true, 512, JSON_THROW_ON_ERROR)];
}示例使用全局文本翻译端点和资源订阅密钥。区域资源通常还需要Ocp-Apim-Subscription-Region,按资源实际区域配置;不要填成用户所在城市或目标语言地区。访问权限、计费和请求字符限制由Azure资源决定。

Azure Translator批量输入的数组结构
把输入ID与各目标语言结果关联
<?php
require __DIR__.'/http.php';
$input=['welcome'=>'Welcome back.','saved'=>'Your changes were saved.'];
$targets=['zh-Hans','de'];
$query='api-version=3.0&from=en';
foreach($targets as $lang){$query.='&to='.rawurlencode($lang);}
$headers=['Ocp-Apim-Subscription-Key: '.getenv('AZURE_TRANSLATOR_KEY')];
if($region=getenv('AZURE_TRANSLATOR_REGION')){$headers[]='Ocp-Apim-Subscription-Region: '.$region;}
$payload=array_map(static fn(string $text):array=>['Text'=>$text],array_values($input));
[$status,$r]=requestJson('POST','https://api.cognitive.microsofttranslator.com/translate?'.$query,$headers,$payload);
if($status!==200||count($r)!==count($input)){throw new RuntimeException('Translation response mismatch');}
$output=[];
foreach(array_keys($input) as $i=>$id){
foreach($r[$i]['translations']??[] as $translation){
$lang=$translation['to'];
if(!in_array($lang,$targets,true)){throw new RuntimeException('Unexpected target');}
$output[$id][$lang]=$translation['text'];
}
if(count($output[$id]??[])!==count($targets)){throw new RuntimeException('Incomplete targets');}
}
echo json_encode($output,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR);
多条输入与多条翻译结果的对应关系
分批时保持键和结果的对应
大数组先按当前字符和元素限制拆批,每批保留输入ID顺序,确认整批成功后再合并。429按服务端要求退避,400先检查语言、参数和长度,401或403检查密钥、区域和资源权限。错误结果不作为空译文覆盖已有文案。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
普通文本使用默认textType;若提交HTML,必须显式选择对应类型并在应用层保护不应翻译的结构。自动语言检测不一定适合短词,已知源语言时像示例一样明确from。

翻译请求的状态码和错误范围


















