如何在Slim中访问POST请求的JSON请求主体?

14 php post json http-post slim

我只是Slim框架中的新手.我使用Slim框架编写了一个API.

POST应用程序将从iPhone应用程序发送到此API.此POST请求采用JSON格式.

但我无法访问iPhone请求中发送的POST参数.当我尝试打印POST参数的值时,每个参数都得到"null".

$allPostVars = $application->request->post(); //Always I get null
Run Code Online (Sandbox Code Playgroud)

然后我尝试获取即将到来的请求的主体,将主体转换为JSON格式并将其作为对iPhone的响应发回.然后我得到了参数的值,但它们的格式非常奇怪,如下所示:

"{\"password\":\"admin123\",\"login\":\"admin@gmail.com\",\"device_type\":\"iphone\",\"device_token\":\"785903860i5y1243i5\"}"
Run Code Online (Sandbox Code Playgroud)

所以有一件事是肯定的,POST请求参数将来到这个API文件.虽然它们无法进入$application->request->post(),但它们正在进入请求体内.

我的第一个问题是如何从请求主体访问这些POST参数,我的第二个问题是为什么请求数据在将请求主体转换为JSON格式后显示为如上所述的奇怪格式?

以下是必要的代码段:

<?php

    require 'Slim/Slim.php';    

    \Slim\Slim::registerAutoloader();

    //Instantiate Slim class in order to get a reference for the object.
    $application = new \Slim\Slim();

    $body = $application->request->getBody();
    header("Content-Type: application/json");//setting header before sending the JSON response back to the iPhone
    echo json_encode($new_body);// Converting the request body into JSON format and sending it as a response back to the iPhone. After execution of this step I'm getting the above weird format data as a response on iPhone.
    die;
?>
Run Code Online (Sandbox Code Playgroud)

gui*_*rae 35

一般来说,您可以通过以下POST两种方式之一单独访问参数:

$paramValue = $application->request->params('paramName');
Run Code Online (Sandbox Code Playgroud)

要么

$paramValue = $application->request->post('paramName');
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅文档:http://docs.slimframework.com/#Request-Variables

在a中发送JSON时POST,您必须访问请求正文中的信息,例如:

$app->post('/some/path', function () use ($app) {
    $json = $app->request->getBody();
    $data = json_decode($json, true); // parse the JSON into an assoc. array
    // do other tasks
});
Run Code Online (Sandbox Code Playgroud)

  • 啊,我现在明白了.然后这是一个副本:http://stackoverflow.com/questions/26346960/how-to-get-the-post-request-entity-using-slim-framwork (2认同)
  • 要阐明:你只需要在请求体上使用`json_decode`来解析响应并获取信息. (2认同)
  • JSON未解析为$ _POST - 它作为请求体的内容发送 - 因此无法使用`post()`和`params()`方法访问它.因此,要获取数据,您必须执行以下操作:`json_encode($ application-> request-> getBody(),true)`将JSON字符串解析为关联数组并按需使用. (2认同)

小智 11

"Slim可以解析开箱即用的JSON,XML和URL编码数据" - http://www.slimframework.com/docs/objects/request.html "请求正文"下.

处理任何正文形式请求的最简单方法是通过"getParsedBody()".这将做guillermoandrae示例,但在1行而不是2行.

例:

$allPostVars = $application->request->getParsedBody();
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过给定数组中的键访问任何参数.

$someVariable = $allPostVars['someVariable'];
Run Code Online (Sandbox Code Playgroud)