note 104511 deleted from function.http-parse-headers by danbrown
| From: | danbrown@php.net | Date: | Mon, 20 Jun 2011 14:21:07 +0000 |
| Subject: | note 104511 deleted from function.http-parse-headers by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-180682@lists.php.net to get a copy of this message | ||
Note Submitter: Ej52
----
The previous submission was good, however when there is more than one
of the same header the function returns a really deep array for that header
Example:
[Set-Cookie] => Array
(
[0] => Array
(
[0] => Array
(
[0] => cookie1=test1;
[1] => cookie2=test2;
)
[1] => cookie3=test3;
)
[1] => cookie4=test4;
)
So i just modified the previous function so it would create a single array of
all the headers that are the same which will produce the following.
Example:
[Set-Cookie] => Array
(
[0] => cookie1=test1;
[1] => cookie2=test2;
[2] => cookie3=test3;
[3] => cookie4=test4;
)
And here is the modified version for those of you not wanting to install PECL :)
<?php
function http_parse_headers( $data ) {
$retVal = array();
$fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ',
$data));
foreach( $fields as $field ) {
if( preg_match('/([^:]+): (.+)/m', $field, $match) ) {
$match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e',
'strtoupper("\0")', strtolower(trim($match[1])));
if( isset($retVal[$match[1]]) ) {
if ( is_array( $retVal[$match[1]] ) ) {
$i = count($retVal[$match[1]]);
$retVal[$match[1]][$i] = $match[2];
}
else {
$retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
}
} else {
$retVal[$match[1]] = trim($match[2]);
}
}
}
return $retVal;
}
?>