从PHP中的$ _POST对象获取键/值的最佳方法是什么?

时间:2017-07-17 07:07:54

标签: php arrays http object post

我有以下对象发布到PHP服务器。

payload={
    "sms_messages": [
        {
            "created": "Tue, 08 Jan 2013 23:25:08 +0000"
            "id": "5e8dd0d21e4b615e588e88848279634a",
            "from": "xxxxxxxxxxx",
            "destination": "xxxxxxxxxx",
            "message": "Hi. This is an inbound message"
        }
    ]
}

我想回复'from'键但是,我不知道如何在PHP中执行此操作。

我的猜测是这样的:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
 echo $_POST['payload']['sms_messages']['from'];
}

但是,这会返回错误:

Illegal string offset 'sms_messages' 

1 个答案:

答案 0 :(得分:0)

$payload = json_decode(file_get_contents('php://input'));
if ($payload && isset($payload->sms_messages) && is_array($payload->sms_messages)) {
  foreach($payload->sms_messages as $msg) {
    // handle each message here, e.g. by accessing $msg->from
    print_r($msg); // debug output
  }
}