代码之家  ›  专栏  ›  技术社区  ›  Marcus J.Kennedy

解码php://inputjson

  •  0
  • Marcus J.Kennedy  · 技术社区  · 8 年前

    我收到了来自 file_get_contents('php://input') :

    [{"email":"text@examlple.com","event":"processed","sg_event_id":"JJTr9qA","sg_message_id":"AjvX5L7IQeGOfxmJV-OCnw","smtp-id":"<AfxmJV-OCnw@ismon1.sendgrid.net>","timestamp":16813363}]
    

    我需要获取单个元素,如电子邮件或事件,但无法获取 json_decode 和其他人一起工作。

    $obj = json_decode(file_get_contents('php://input'));
    

    如何引用json数据中的单个元素?

    2 回复  |  直到 8 年前
        1
  •  5
  •   Felippe Duarte    8 年前

    您有一个数组,因此需要获取第一个元素:

    $json = '[{"email":"text@examlple.com","event":"processed","sg_event_id":"JJTr9qA","sg_message_id":"AjvX5L7IQeGOfxmJV-OCnw","smtp-id":"<AfxmJV-OCnw@ismon1.sendgrid.net>","timestamp":16813363}]';
    
    $obj = json_decode($json);
    echo $obj[0]->email; //output text@examlple.com
    
        2
  •  -2
  •   Chris    8 年前

    给你一个完整的答案:

    <?php
    
    $str = '[{"email":"text@examlple.com","event":"processed","sg_event_id":"JJTr9qA","sg_message_id":"AjvX5L7IQeGOfxmJV-OCnw","smtp-id":"<AfxmJV-OCnw@ismon1.sendgrid.net>","timestamp":16813363}]';
    
    $obj = json_decode($str);
    
    echo $obj[0]->email;
    
    推荐文章