多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## 请求主体 Every HTTP request has a body. If you are building a Slim application that consumes JSON or XML data, you can use the PSR-7 Request object’s`getParsedBody()`method to parse the HTTP request body into a native PHP format. Note that body parsing differs from one PSR-7 implementation to another. > 每个HTTP请求都有一个主体。如果您正在构建一个使用JSON或XML数据的slim应用程序,那么可以使用PSR-7请求对象的`getParsedBody()`方法将HTTP请求体解析为原生PHP格式。注意,不同的PSR-7实现之间的主体解析是不同的。 You may need to implement middleware in order to parse the incoming input depending on the PSR-7 implementation you have installed. Here is an example for parsing incoming`JSON`input: > 您可能需要实现中间件,以便根据安装的PSR-7实现来解析输入。下面是一个解析传入`JSON`输入的例子: ~~~php <?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); } } ~~~ ~~~php $parsedBody = $request->getParsedBody(); ~~~ Figure 9: Parse HTTP request body into native PHP format Technically speaking, the PSR-7 Request object represents the HTTP request body as an instance of`Psr\Http\Message\StreamInterface`. You can get the HTTP request body`StreamInterface`instance with the PSR-7 Request object’s`getBody()`method. The`getBody()`method is preferable if the incoming HTTP request size is unknown or too large for available memory. > 从技术上讲,Psr -7请求对象将HTTP请求体表示为`Psr\ HTTP \Message\StreamInterface`的一个实例。您可以使用PSR-7请求对象的`getBody()`方法获得HTTP请求体`StreamInterface`实例。如果传入的HTTP请求大小未知或者对于可用内存来说太大,则使用`getBody()`方法更好。 ~~~php $body = $request->getBody(); ~~~ Figure 10: Get HTTP request body The resultant`Psr\Http\Message\StreamInterface`instance provides the following methods to read and iterate its underlying PHP`resource`. > 由此产生的`Psr\Http\Message\StreamInterface`实例提供了以下方法来读取和迭代它的底层PHP`资源`。 * getSize() * tell() * eof() * isSeekable() * seek() * rewind() * isWritable() * write($string) * isReadable() * read($length) * getContents() * getMetadata($key = null)