I am currently working on the response from the 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).
Just like the API manual, I do the following:
try
{
$response = $request->send();
echo $response->getBody();
}
What I got is like this:
[
{
"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
}
}
]
However, I only want some aspect of the "scores", like "anger" or "happiness". I tried to use json_decode on $response
but I got an error:json_decode() expects parameter 1 to be string, object given
. It seems that HTTP_Request2_Response provide me an object. How do I extract the data I want from the response?
Here is the var_dump
of $response
for your reference:
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)
$jsonString = $response->getBody();
$bodyAsArray = json_decode($jsonString, true); // true returns associative array
echo $bodyAsArray['scores']['anger'];