简体   繁体   English

如何在PHP中将标题和正文一起输出?

[英]How to output headers together with body in PHP?

There's a string like: 有一个像这样的字符串:

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>
...

Is is possible to send it as headers + body with one command? 是否可以通过一个命令将其作为标头+正文发送? I know you can use header and echo/print/printf to output body, but since the string I have is exactly in the form I've written, to use these functions I'd have to parse it into headers and body. 我知道您可以使用header和echo / print / printf来输出主体,但是由于我拥有的字符串恰好是我编写的形式,因此要使用这些功能,我必须将其解析为标头和主体。

I've tried writing to php://output , but it seems to think headers are the body. 我试着写到php://output ,但是似乎认为标题是主体。

No, you have to use header() . 不,您必须使用header() You could split the string into lines, walk the lines one by one calling header() for each one until you meet the empty line and then echo the rest of it. 您可以将字符串拆分为几行,逐行逐行调用header() ,直到遇到空行,然后回显其余行。

There is no way (AFAIK) to write the headers to output as a raw string - PHP and the web server handle this silently in the background, to ensure the response is valid - but splitting to headers/body is easy enough: 没有方法(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);

}

As long as your response string conforms to the HTTP standard, this will work perfectly. 只要您的响应字符串符合HTTP标准,它就可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM