请求正文

每个 HTTP 请求都有一个正文。如果你正在构建一个消费 JSON 或 XML 数据的 Slim 应用程序,你可以使用 PSR-7 Request 对象的 getParsedBody() 方法将 HTTP 请求正文解析为本机 PHP 格式。请注意,不同的 PSR-7 实现在正文解析方面可能存在差异。

根据你安装的 PSR-7 实现,你可能需要实现中间件来解析传入的输入。下面是一个用于解析传入的 JSON 输入的示例:

<?php

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;

class JsonBodyParserMiddleware implements MiddlewareInterface
{
    public function process(Request $request, RequestHandler $handler): Response
    {
        $contentType = $request->getHeaderLine('Content-Type');

        if (strstr($contentType, 'application/json')) {
            $contents = json_decode(file_get_contents('php://input'), true);
            if (json_last_error() === JSON_ERROR_NONE) {
                $request = $request->withParsedBody($contents);
            }
        }

        return $handler->handle($request);
    }
}
$parsedBody = $request->getParsedBody();

从技术上讲,PSR-7 Request 对象将 HTTP 请求正文表示为 Psr\Http\Message\StreamInterface 的实例。你可以使用 PSR-7 Request 对象的 getBody() 方法获取 HTTP 请求正文的 StreamInterface 实例。如果传入的 HTTP 请求大小未知或太大而无法放入内存中,getBody() 方法更可取。

$body = $request->getBody();

返回的 Psr\Http\Message\StreamInterface 实例提供以下方法来读取和迭代其底层 PHP resource

  • getSize()
  • tell()
  • eof()
  • isSeekable()
  • seek()
  • rewind()
  • isWritable()
  • write($string)
  • isReadable()
  • read($length)
  • getContents()
  • getMetadata($key = null)