【问题标题】:Extract data from HTTP_Request2_Response object using PHP使用 PHP 从 HTTP_Request2_Response 对象中提取数据
【发布时间】:2018-03-06 23:38:27
【问题描述】:

我目前正在处理来自Microsoft Emotion API 的回复。在 API 中,使用了HTTP/Request2.php,我在 HTTP_Request2_Response(Manual here) 中使用 getBody() 成功获取了 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 为我提供了一个对象。如何从响应中提取我想要的数据?

这是$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) 

【问题讨论】:

    标签: php json api pear http-request2


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:
      $jsonString = $response->getBody();
      $bodyAsArray = json_decode($jsonString, true); // true returns associative array
      echo $bodyAsArray['scores']['anger'];
      

      【讨论】:

      • 谢谢!我现在可以得到价值了!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      • 2020-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多