我目前正在处理来自Microsoft Emotion API的响应。在 APIHTTP/Request2.php
中,我使用getBody()
HTTP_Request2_Response (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
}
}
]
但是,我只想要“分数”的某些方面,例如“愤怒”或“快乐”。我尝试使用 json_decode on$response
但出现错误: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)