在PHP Microsoft Cognitive Services中使用cURL获取HTTP POST请求的无效输入记录


Getting invalid input records for HTTP POST request using cURL in PHP Microsoft Cognitive Services

这让我快疯了。使用微软的认知服务,我尝试用PHP和cURL向情感分析RESTful服务发布一些文本。我感觉我已经按照这里的说明做了https://westus.dev.cognitive.microsoft.com/docs/services/TextAnalytics.V2.0/operations/56f30ceeeda5650db055a3c9

但是我无论如何也不能让我的代码工作。

$body = array(
    "documents" => array(
    "language" => "en",
    "id" => "one",
    "text" => "Well, look, you look back at George W. Bush’s administration, he selected people who were very close to his family, to his father, and so you do see some of that. But it’s interesting.",
     ),
   );
$API_Endpoint ="https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment";
$headers = ['Content-Type: application/json','Ocp-Apim-Subscription-Key:{myactualkeyhere}',];
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TRANSFERTEXT, true);
$result = curl_exec($ch);
curl_close($ch);
echo json_encode($result);
我返回的错误是
"{'"code'":'"BadRequest'",'"message'":'"Invalid request'",'"innerError'":{'"code'":'"InvalidRequestContent'",'"message'":'"Missing input records.'"}}"

所以我能够回答我自己的问题经过深思熟虑和尝试和错误。最初我认为这个问题是与我的头,我不断得到错误回来需要一个API密钥,即使它显然是在头。但这个问题原来是一个非常基本的PHP数组创建问题,我只是错过了,因为我是一个新手。

正确的数组语法是:
                   $body = array (
                                  'documents' => 
                                  array (
                                    0 => 
                                    array (
                                      'language' => 'en',
                                      'id' => 'one',
                                      'text' => $text,
                                    ),
                                  ),
                                );

我希望这能帮助其他像我一样尝试在PHP中卷曲RESTful API端点的新手。好运!