就像完成,即使這個問題是兩年多歲:
響應是由服務器發送到客戶端的HTTP消息,作爲從客戶端到服務器的請求的結果。
客戶端需要字符串消息,組成:
- 一個 「狀態行」(在形式
HTTP/<protocol-version> <status-code> <reason-phrase>
);
- 一個列表標題(每個形式爲「
<header-name>: <comma-separ.-header-values>
」);
- 空行;
- a 消息體(一個字符串)。
而且它看起來像這樣(見PSR-7):
HTTP/1.1 200 OK
Content-Type: text/html
vary: Accept-Encoding
This is the response body
爲了發出響應,必須實際執行三種操作:
- 發送「狀態行「給客戶端(使用PHP函數header())。
- 發送標題列表到客戶端(dito)。
- 輸出消息正文。
棘手的部分是由第三個操作代表。一個實現ResponseInterface
的類的實例包含一個流對象作爲消息體。而且這個對象必須轉換成一個字符串並打印出來。該任務可以很容易地完成,因爲該流是實現StreamInterface
的類的實例,其反過來又強制實施了神奇方法__toString()的定義。
因此,通過執行前兩個步驟並對響應實例的getBody()
方法的結果應用輸出函數(echo
,print_r
等),發射過程就完成了。
<?php
if (headers_sent()) {
throw new RuntimeException('Headers were already sent. The response could not be emitted!');
}
// Step 1: Send the "status line".
$statusLine = sprintf('HTTP/%s %s %s'
, $response->getProtocolVersion()
, $response->getStatusCode()
, $response->getReasonPhrase()
);
header($statusLine, TRUE); /* The header replaces a previous similar header. */
// Step 2: Send the response headers from the headers list.
foreach ($response->getHeaders() as $name => $values) {
$responseHeader = sprintf('%s: %s'
, $name
, $response->getHeaderLine($name)
);
header($responseHeader, FALSE); /* The header doesn't replace a previous similar header. */
}
// Step 3: Output the message body.
echo $response->getBody();
exit();
P.S:對於大數據量的,最好使用php://temp
流,而不是php://memory
。 Here是原因。
你打算使用哪個框架? 你可以看看他們的例子,看他們如何利用PSR-7。例如Slim框架https://www.slimframework.com/ – nohponex