user3736514
user3736514

Reputation: 13

Parsing a JSON array with PHP 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?

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)
        "close"
    }
    ["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 ":"[email protected] ",
            "message ":"test ",
        },
        "enquiries":null
    } 
    ["response"] => array(2) {
        ["code"] => int(202)
        ["message"] => string(8)
        "Accepted"
    }
    ["cookies"] => array(0) {}
    ["filename"] => NULL
}

Upvotes: 0

Views: 35

Answers (1)

Alexis Côté
Alexis Côté

Reputation: 3690

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.

Upvotes: 1

Related Questions