user3736514 user3736514 - 3 months ago 4
PHP Question

PHP: Parse a an JSON array does not work

From the service request I get the following response and I have tried json_decode to parse it but it does not work. I need to check if
["body"]->enquiry->status is 'OPEN'. Could anyone tell me how to parse this response? Thanks in advance.

array(5) {
["headers"] => array(5) {
["server"] => string(17)
"Apache-Coyote/1.1" ["content-type"] => string(16)
"application/json" ["content-length"] => string(3)
"313" ["date"] => string(29)
"Fri, 08 Jul 2016 00:22:29 GMT" ["connection"] => string(5)
["body"] => string(313){
"version ":{
"major ":1,
"minor ":6,
"revision ":0
"enquiry ":{
"id ":"21a2a688-c09b-48bc-8cb0-0ad596c18447",
"creationTime ":1467937344745,
"lastUpdateTime ":1467937344753,
"status ":"OPEN ",
"from ":"test ",
"email ":" ",
"message ":"test ",
["response"] => array(2) {
["code"] => int(202)
["message"] => string(8)
["cookies"] => array(0) {}
["filename"] => NULL


Here's how to access it. I used the $response as the response you gave us.

//We decode the 'body' from the response to json and we convert it to an array
$body = json_decode($response['body'],true);

//We access the status
$status = $body['enquiry']['status'];

Also, be careful if you want to check if the status is equal to 'OPEN'. In you response, the status is actual OPEN. Notice the trailing space. You can use trim($status) to remove the spaces.