简体   繁体   English

如何使用 PHP 提取 JSON 数据

[英]How to extract JSON data with PHP

I'm trying to extract the value from the event key (delivered) using PHP.我正在尝试使用 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这是我的 JSON 文件

{ 
   "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.第一个问题是您的 JSON 文件格式错误。 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.其次, $status[1]['event']也是错误的。 You should use $status['events'] .您应该使用$status['events']

I figured it out.我想到了。 So I am parsing a json response from CURL...所以我正在解析来自 CURL 的 json 响应......

$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!感谢所有伸出援手的人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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