Created
August 29, 2018 04:51
Star
You must be signed in to star a gist
Parse the side effect variable $http_response_header of file_get_contents().
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
}, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example use: