## 响应体
An HTTP response typically has a body.
> HTTP响应通常有一个主体。
Just like the PSR-7 Request object, the PSR-7 Response object implements the body as an instance of`Psr\Http\Message\StreamInterface`. You can get the HTTP response body`StreamInterface`instance with the PSR-7 Response object’s`getBody()`method. The`getBody()`method is preferable if the outgoing HTTP response length is unknown or too large for available memory.
> 与Psr -7请求对象一样,Psr -7响应对象将主体作为`Psr\Http\Message\StreamInterface`的实例实现。您可以使用PSR-7响应对象的`getBody()`方法获得HTTP响应体`StreamInterface`实例。如果传出HTTP响应长度未知或对于可用内存来说太大,则使用`getBody()`方法更好。
~~~php
$body = $response->getBody();
~~~
Figure 12: Get HTTP response body
The resultant`Psr\Http\Message\StreamInterface`instance provides the following methods to read from, iterate, and write to 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)
Most often, you’ll need to write to the PSR-7 Response object. You can write content to the`StreamInterface`instance with its`write()`method like this:
> 通常,您需要向PSR-7响应对象写入内容。你可以用它的`write()`方法将内容写入`StreamInterface`实例,如下所示:
~~~php
$body = $response->getBody();
$body->write('Hello');
~~~
Figure 13: Write content to the HTTP response body
You can also*replace*the PSR-7 Response object’s body with an entirely new`StreamInterface`instance. This is particularly useful when you want to pipe content from a remote destination (e.g. the filesystem or a remote API) into the HTTP response. You can replace the PSR-7 Response object’s body with its`withBody(StreamInterface $body)`method. Its argument**MUST**be an instance of`Psr\Http\Message\StreamInterface`.
> 您还可以用一个全新的`StreamInterface`实例`替换`PSR-7响应对象的主体。当您希望将内容从远程目标(例如文件系统或远程API)导入HTTP响应时,这一点特别有用。您可以用它的`withbody (StreamInterface $body)`方法替换PSR-7响应对象的主体。它的参数**必须是`Psr\Http\Message\StreamInterface`的一个实例。
~~~php
use GuzzleHttp\Psr7\LazyOpenStream;
$newStream = new LazyOpenStream('/path/to/file', 'r');
$newResponse = $oldResponse->withBody($newStream);
~~~
Figure 14: Replace the HTTP response body
**Reminder**
The Response object is immutable. This method returns a*copy*of the Response object that contains the new body.
> 提醒
> Response对象是不可变的。此方法返回包含新主体的响应对象的副本。
- 开始
- 安装
- 升级指南
- Web服务器
- 概念
- 生命周期
- PSR 7
- 中间件
- 依赖容器
- 实例 及通知和警告处理
- Request
- 请求方法
- 请求头信息
- 请求主体
- 上传的文件
- 请求帮助
- 路由对象
- Response
- 响应状态
- 响应标头
- 响应体
- 返回JSON
- 视图模板
- 路由
- 创建路由
- 路由回调
- 路由策略
- 路线占位符
- 路由名
- 路由组
- 路由中间件
- 路由表达式缓存
- 容器识别解析
- 封装中间件
- 路由的中间件
- 错误处理中间件
- 方法重写的中间件
- 输出缓冲中间件
- 内容长度中间件
- 扩展功能
- 以 / 结尾的路由模式
- 获取当前路由
- 设置CORS
- 使用POST表单上传文件
- 第三方组件
- slim-session
- auth
- slim-api-skeleton
- dir