简体   繁体   中英

How to extract JSON data with PHP

I'm trying to extract the value from the event key (delivered) using PHP. I thought the follow would work below but I'm getting no results. I know this is probably a simple thing to do and probably looking too far into it.

How I am trying to extract the value

$status = json_decode($status, true);
echo $status[1]['event'];


Here is my JSON file

{ 
   "events":[ 
      { 
         "email":"email@gmail.com",
         "date":"2020-02-17T22:16:58.000+01:00",
         "subject":"PHPMailer SMTP test",
         "messageId":"<hdskjfjsdhfsjdkfdksh>",
         "event":"delivered",
         "tag":"",
         "from":"test@gmail.com"
      }
   ]
}

Any help would be appreciated :)

The first issue is that your JSON file is wrong formatted. It should be:

{
 "events": [
  {
   "email": "email@gmail.com",
   "date": "2020-02-17T22:16:58.000+01:00",
   "subject": "PHPMailer SMTP test",
   "messageId": "74483437597589347843758934759",
   "event": "delivered",
   "tag": "",
   "from": "test@gmail.com"
  }
 ]
}

Second, $status[1]['event'] is also wrong. You should use $status['events'] .

I figured it out. So I am parsing a json response from CURL...

$response = curl_exec($curl);

I changed this

$status = json_decode($status, true);
echo $status['events'][0]['event'];

to

$status = json_decode($response, true);
echo $status['events'][0]['event'];

I totally missed that mistake. Thanks to everyone who reach out!

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