简体   繁体   中英

Curl Response Echo / Store in PHP

I am using following curl code in my script

            $ch = curl_init(self::ONTRAPORT_API_ENDPOINT);
            curl_setopt($ch, CURLOPT_HTTPHEADER, self::$ONTRAPORT_AUTH_HEADERS);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $response = curl_exec($ch);
            $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

        //echo $status_code;
            if ($status_code === 200 || $status_code === 201) {
$jsonen = json_decode($response, true);
                $accountId = $jsonen['id'];     // this is not working
            }

What I am trying to do is to declare "id" that I get in curl response. Please check the comment in code above. But I am not able to get id stored in variable $accountId.

My curl response is something like this

{
  "code": 0,
  "data": {
    "firstname": "test1",
    "lastname": "test2",
    "email": "test1@test.net",
    "id": "39948"
  },
  "updates": [],
  "notifications": [],
  "account_id": "26615"
}

So I need "39948" get stored in my variable. Please advise.

JSON is a hierarchy of data. The "id" key is underneath "data", so you access it like this:

$jsonen['data']['id'];
$the_id =  $jsonen->data-id; //save the ID in a variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM