如何正确处理 PHP post 请求?

我正在制作一个小型 API 来处理一些调查。


我有以下身体:


{

  "name":"1: asd",

  

  "children":[

     {

        "name":"2: are",

        "children":[

           {

              "name":"3: wat wat",

              "children":[

                 {

                    "name":"4: in da hut",

                    "context":{

                       "question":"in da hut",

                       "questionType":"rbText",

                       "answers":[

                          {

                             "value":"",

                             "index":0,

                             "indexValue":1

                          }

                       ]

                    }

                 },

                 {

                    "name":"5: k k k k",

                    "context":{

                       "question":"k k k k",

                       "questionType":"rbText",

                       "answers":[

                          {

                             "value":"",

                             "index":0,

                             "indexValue":1

                          }

                       ]

                    }

                 }

              ],

              "context":{

                 "question":"wat wat",

                 "questionType":"rbMultiple",

                 "answers":[

                    {

                       "value":"sim",

                       "index":2,

                       "indexValue":4

                    },

                    {

                       "value":"nao",

                       "index":3,

                       "indexValue":5

                    }

                 ]

              }

           }

        ],

        "context":{

           "question":"are",

           "questionType":"rbMultiple",

           "answers":[

              {

                 "value":"potatoes",

                 "index":4,

                 "indexValue":3

              },

              {

                 "value":"nay",

                 "index":4,

                 "indexValue":3

              }

           ]

        }

     }


我究竟做错了什么?

白衣染霜花
浏览 80回答 2
2回答

白衣非少年

您首先需要访问请求的整个正文:$post_body = file_get_contents("php://input");然后,因为这返回一个字符串,所以您需要解码JSON:$content = json_decode($post_body);然后您将拥有一个代表请求正文的对象,name可以使用箭头运算符检索该对象:echo $content->name

牛魔王的故事

来自$_POST文档(强调我的):当使用application/x-www-form-urlencoded或multipart/form-data作为请求中的HTTP Content-Type时,通过 HTTP POST 方法传递到当前脚本的变量的关联数组。任何其他 MIME 类型(application/json, application/xml...)都不会自动解码,需要您自己解析。
打开App,查看更多内容
随时随地看视频慕课网APP