有一个像这样的字符串:
HTTP/1.1 200 OK
Date: Thu, 15 Dec 2011 12:23:25 GMT
Server: Microsoft-IIS/6.0
Content-Length: 2039
Content-Type: text/html
<!DOCTYPE html>
...
Run Code Online (Sandbox Code Playgroud)
是否可以使用一个命令将其作为标题 + 正文发送?我知道您可以使用headerecho/print/printf 来输出正文,但是由于我拥有的字符串与我编写的格式完全相同,因此要使用这些函数,我必须将其解析为标题和正文。
我试过写信给php://output,但它似乎认为标题是正文。
没有办法 (AFAIK) 将标头写入作为原始字符串输出 - PHP 和 Web 服务器在后台静默处理,以确保响应有效 - 但拆分为标头/正文很容易:
function output_response_string ($responseStr) {
// Split the headers from the body and fetch the headers
$parts = explode("\r\n\r\n", $responseStr);
$headers = array_shift($parts);
// Send headers
foreach (explode("\r\n", $headers) as $header) {
$header = trim($header);
if ($header) header($header);
}
// Send body
echo implode("\r\n\r\n", $parts);
}
Run Code Online (Sandbox Code Playgroud)
只要您的响应字符串符合 HTTP 标准,这将完美运行。