为了账号安全,请及时绑定邮箱和手机立即绑定

如何正确处理 PHP post 请求?

如何正确处理 PHP post 请求?

PHP
白衣染霜花 2023-06-24 15:10:57
我正在制作一个小型 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              }           ]        }     }我究竟做错了什么?
查看完整描述

2 回答

?
白衣非少年

TA贡献1155条经验 获得超0个赞

您首先需要访问请求的整个正文:

$post_body = file_get_contents("php://input");

然后,因为这返回一个字符串,所以您需要解码JSON

$content = json_decode($post_body);

然后您将拥有一个代表请求正文的对象,name可以使用箭头运算符检索该对象:

echo $content->name


查看完整回答
反对 回复 2023-06-24
?
牛魔王的故事

TA贡献1830条经验 获得超3个赞

来自$_POST文档(强调我的):

当使用application/x-www-form-urlencodedmultipart/form-data作为请求中的HTTP Content-Type时,通过 HTTP POST 方法传递到当前脚本的变量的关联数组。

任何其他 MIME 类型(application/jsonapplication/xml...)都不会自动解码,需要您自己解析。


查看完整回答
反对 回复 2023-06-24
  • 2 回答
  • 0 关注
  • 78 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信