Also, here is a modified version that will return the header as a string, and will include the initial "HTTP/1.x" status lines in the header result:
function http_parse_response($string)
{
$header = null;
$header_values_begun = false;
$content = null;
$str = strtok($string, "\n");
$h = null;
while ($str !== false)
{
if ($h && trim($str) === '')
{
$h = false;
continue;
}
if ($h !== false)
{
$header .= $str."\n";
$h = strpos($str, ':') === false ? null : true;
}
if ($h === false)
{
$content .= $str."\n";
}
$str = strtok("\n");
}
return array($header, trim($content));
}
http_parse_message
(PECL pecl_http >= 0.12.0)
http_parse_message — Parse HTTP messages
Descrição
object http_parse_message
( string $message
)
Parses the HTTP message into a simple recursive object.
Parâmetros
- message
-
string containing a single HTTP message or several consecutive HTTP messages
Valor Retornado
Returns a hierarchical object structure of the parsed messages.
Exemplos
Exemplo #1 Using http_parse_message()
<?php
define ('URL', 'http://www.example.com/');
print_r(http_parse_message(http_get(URL, array('redirect' => 3))));
?>
O exemplo acima irá imprimir algo similar a:
stdClass object
(
[type] => 2
[httpVersion] => 1.1
[responseCode] => 200
[headers] => Array
(
[Content-Length] => 3
[Server] => Apache
)
[body] => Hi!
[parentMessage] => stdClass object
(
[type] => 2
[httpVersion] => 1.1
[responseCode] => 302
[headers] => Array
(
[Content-Length] => 0
[Location] => ...
)
[body] =>
[parentMessage] => ...
)
)
User Contributed Notes
http_parse_message
http_parse_message
A.S.
16-Jan-2011 09:16
16-Jan-2011 09:16
A.S.
16-Jan-2011 09:02
16-Jan-2011 09:02
A useful function, but I couldn't use it because it's not installed on my host. Here's an alternative I found at http://snipplr.com/view/17242/parse-http-response/ :
function parse_http_response ($string)
{
$headers = array();
$content = '';
$str = strtok($string, "\n");
$h = null;
while ($str !== false) {
if ($h and trim($str) === '') {
$h = false;
continue;
}
if ($h !== false and false !== strpos($str, ':')) {
$h = true;
list($headername, $headervalue) = explode(':', trim($str), 2);
$headername = strtolower($headername);
$headervalue = ltrim($headervalue);
if (isset($headers[$headername]))
$headers[$headername] .= ',' . $headervalue;
else
$headers[$headername] = $headervalue;
}
if ($h === false) {
$content .= $str."\n";
}
$str = strtok("\n");
}
return array($headers, trim($content));
}

http_parse_headers