note 123086 deleted from function.file-get-contents by salathe
| From: | salathe@php.net | Date: | Mon, 21 Sep 2020 14:39:32 +0000 |
| Subject: | note 123086 deleted from function.file-get-contents by salathe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-215254@lists.php.net to get a copy of this message | ||
Note Submitter: koalay at gmail dot com
----
A simple way to parse side effect array $http_response_header into a better assoc format.
<?php
/**
* http_parse_response_header()
* Parse $http_response_header produced by file_get_contents().
*
* @param array $header
* Supposed $http_response_header or array alike.
* @param array
* Assoc array of the parsed version.
*/
function http_parse_response_header($header) {
if (empty($header)) return []; // return empty array
// parse status line
$status_line = array_shift($header);
if (!preg_match('/^(\w+)\/(\d+\.\d+) (\d+) (.+?)$/', $status_line, $matches))
throw new Exception("misformat status line: {$status_line}");
return [
'PROTOCOL' => $matches[1],
'PROTOCOL_VERSION' => $matches[2],
'STATUS_CODE' => $matches[3],
'STATUS' => $matches[4],
] + array_reduce($header, function ($carry, $line) {
// parse content line
list($key, $value) = explode(':', $line, 2);
if (!isset($carry[$key])) {
$carry[$key] = trim($value);
} else {
$carry[$key] .= "\n" . trim($value);
}
return $carry;
}, []);
}
?>
Also added to Github Gist:
https://gist.github.com/yookoala/017f056c34a169514fbf0cd7cc5b2e78