## 響應體
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