使用 PHP 从 HTTP_Request2_Response 对象中提取数据

Extract data from HTTP_Request2_Response object using PHP

我目前正在处理 Microsoft Emotion API. In the API, HTTP/Request2.php is used and I successfully get the HTTP response message by using getBody() in HTTP_Request2_Response(Manual here) 的回复。 就像 API 手册一样,我执行以下操作:

try
{
    $response = $request->send();
    echo $response->getBody();
}

我得到的是这样的:

[
  {
    "faceRectangle": {
      "height":264,
      "left":162,
      "top":523,
      "width":264,

    },
    "scores": {
      "anger":1.38974974E-06,
      "contempt":2.75673688E-08,
      "disgust":3.75520244E-06,
      "fear":5.69216375E-11,
      "happiness":0.999994636,
      "neutral":1.77765841E-07,
      "sadness":3.03275627E-09,
"surprise":2.25669652E-08
    }
  }
]

但是,我只想要 "scores" 的某些方面,例如 "anger" 或 "happiness"。我尝试在 $response 上使用 json_decode,但出现错误:json_decode() expects parameter 1 to be string, object given。 HTTP_Request2_Response 好像给了我一个对象。如何从响应中提取我想要的数据?

这里是$responsevar_dump供大家参考:

object(HTTP_Request2_Response)#5 (9) { 
["version":protected]=> string(3) "1.1" 
["code":protected]=> int(200) 
["reasonPhrase":protected]=> string(2) "OK" 
["effectiveUrl":protected]=> string(65) "https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize" 
["headers":protected]=> array(10) { 
["cache-control"]=> string(8) "no-cache" 
["pragma"]=> string(8) "no-cache" 
["content-length"]=> string(3) "274" 
["content-type"]=> string(31) "application/json; charset=utf-8" 
["expires"]=> string(2) "-1" 
["x-powered-by"]=> string(7) "ASP.NET" 
["apim-request-id"]=> string(36) "96fgh4z1-62z0-43r3-82z7-8823hdg5g86d" 
["strict-transport-security"]=> string(44) "max-age=31536000; includeSubDomains; preload" 
["x-content-type-options"]=> string(7) "nosniff" 
["date"]=> string(29) "Tue, 06 Mar 2018 14:55:20 GMT" } 
["cookies":protected]=> array(0) { } 
["lastHeader":protected]=> string(4) "date" 
["body":protected]=> string(274) "
[{"faceRectangle":{"height":264,"left":162,"top":523,"width":264},
"scores":{"anger":1.38974974E-06,"contempt":2.75673688E-08,"disgust":3.75520244E-06,"fear":5.69216375E-11,"happiness":0.999994636,"neutral":1.77765841E-07,"sadness":3.03275627E-09,"surprise":2.25669652E-08}}]" 
["bodyEncoded":protected]=> bool(true) 

如果您认为您的响应是一个对象,请尝试使用此代码。

$response = json_decode(json_encode($response), true);

它将return一个数组而不是对象,然后您可以轻松访问数据。

$jsonString = $response->getBody();
$bodyAsArray = json_decode($jsonString, true); // true returns associative array
echo $bodyAsArray['scores']['anger'];