Azure AI服务PHP调用需用REST API;Text Analytics和Computer Vision主流用订阅密钥认证,Speech SDK强制要求AAD token;Text Analytics请求body必须为含id/language/text的documents数组;Computer Vision传图须用multipart而非JSON。

PHP 调用 Azure AI 服务(如 Text Analytics、Computer Vision、Speech SDK 等)本身没有官方 PHP SDK,必须走 REST API;直接用 curl 或 guzzlehttp/guzzle 是唯一稳定路径。
怎么拿到有效的 Azure AI 认证 token?
Azure AI 服务多数使用基于订阅密钥(subscription-key)或 Azure Active Directory(AAD)令牌的认证方式。Text Analytics 和 Computer Vision 当前仍主流用密钥,Speech SDK 则强制要求 AAD token(通过 client_id/client_secret 换取)。
- 密钥方式:在请求头中加
Ocp-Apim-Subscription-Key: <your-key>,无需额外 token 获取步骤 - AAD 方式(如 Speech-to-Text):需先向
https://api.cognitive.microsoft.com/sts/v1.0/issuetokenPOST 请求,带Authorization: Bearer <access-token>(该 access-token 需先用 Azure AD 应用凭证换取) - 注意 endpoint 地址格式:不是通用
https://<region>.api.cognitive.microsoft.com就行,Speech 服务必须用https://<region>.stt.speech.microsoft.com,写错会返回404或401
用 curl 发起 Text Analytics API 请求时要注意什么?
Text Analytics v3.1(当前稳定版)要求 body 必须是 JSON 数组,且字段名严格为 documents,不能是 texts 或 input;同时每个 document 必须含 id、language、text 三者。
- 错误示例:
{"text": "hello"}→ 返回"Invalid request body" - 正确结构:
{"documents": [{"id": "1", "language": "en", "text": "Hello world"}]} - 别漏设
Content-Type: application/json和Ocp-Apim-Subscription-Key头,否则返回400或401 - region 必须和资源创建时选的一致,比如资源在
westus2,就别用eastus的 endpoint,否则报403 Forbidden
为什么 Guzzle 发送 Computer Vision API 总是 400?
Computer Vision 的 analyze 接口接受两种输入:URL(url 字段)或二进制图像(multipart/form-data)。Guzzle 默认把数组转成 application/json,但图像分析必须用表单提交 —— 这是 400 最常见原因。
立即学习“PHP免费学习笔记(深入)”;
- 传图 URL:body 设为
["url" => "https://..."],header 保持Content-Type: application/json - 传本地图片:必须用
multipart,例如['multipart' => [['name' => 'url', 'contents' => file_get_contents($path)]]],此时 header 不能手动设Content-Type(Guzzle 会自动生成 boundary) - 图片大小上限是 4MB,超限返回
"Image size is too large",别硬扛,先getimagesize()校验 - 支持格式有限:仅
jpeg、png、gif、bmp;传webp会静默失败(返回空categories)
真正卡住人的地方,往往不是调不通,而是错误信息太泛(比如一堆 400),而 Azure 的响应体里其实有具体提示字段(如 error.message),建议每次请求后都 var_dump(json_decode($response->getBody(), true)) 看清真实原因。



















