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

问题描述 投票:0回答:2

我目前正在研究Microsoft Emotion API的回应。在API中,使用HTTP/Request2.php并通过在HTTP_Request2_ResponsegetBody()中使用(Manual here)成功获取HTTP响应消息。就像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
    }
  }
]

但是,我只想要“得分”的某些方面,比如“愤怒”或“幸福”。我试图在$response上使用json_decode,但是我收到了一个错误:json_decode() expects parameter 1 to be string, object given。似乎HTTP_Request2_Response为我提供了一个对象。如何从响应中提取我想要的数据?

以下是var_dump$response供您参考:

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) 
php json api pear http-request2
2个回答
0
投票
$jsonString = $response->getBody();
$bodyAsArray = json_decode($jsonString, true); // true returns associative array
echo $bodyAsArray['scores']['anger'];

0
投票

如果您认为您的回复是对象请尝试使用此代码。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.