pgt*_*ips 7 php api rest http-headers
我已经向REST API发出了oauth签名请求,并在数组中包含响应头,如下所示:
[0] => HTTP/1.1 200 OK
[1] => Cache-Control: private
[2] => Transfer-Encoding: chunked
[3] => Content-Type: text/html; charset=utf-8
[4] => Content-Location: https://***
[5] => Server: Microsoft-IIS/7.0
[6] => Set-Cookie: ASP.NET_SessionId=***; path=/; HttpOnly
[7] => X-AspNetMvc-Version: 2.0
[8] => oauth_token: ***
[9] => oauth_token_secret: ***
[10] => X-AspNet-Version: 4.0.30319
[11] => X-Powered-By: ASP.NET
[12] => Date: Sat, 15 Sep 2012 02:01:15 GMT
Run Code Online (Sandbox Code Playgroud)
我试图找出如何解析标题以便轻松检索项目,如HTTP状态代码,Content-Location,oauth_token和oauth_token_secret?
您需要迭代数组并检查stripos()以查找您要查找的标头.在大多数情况下,你再explode()上:(限制到2个得到部分),但HTTP响应代码将要求您在空间爆炸.
// Get any header except the HTTP response...
function getResponseHeader($header, $response) {
foreach ($response as $key => $r) {
// Match the header name up to ':', compare lower case
if (stripos($r, $header . ':') === 0) {
list($headername, $headervalue) = explode(":", $r, 2);
return trim($headervalue);
}
}
}
// example:
echo getResponseHeader("Content-Type");
// text/html; charset=utf-8
// Get the HTTP response code
foreach ($response as $key => $r) {
if (stripos($r, 'HTTP/1.1') === 0) {
list(,$code, $status) = explode(' ', $r, 3);
echo "Code: $code, Status: $status";
break;
}
}
Run Code Online (Sandbox Code Playgroud)
似乎唯一的标题:是HTTP版本和状态.做一个array_shift提取,迭代通过其他人创建一个数组,如下所示:
$parsedHeaders = array();
foreach ($headers as $header) {
if (! preg_match('/^([^:]+):(.*)$/', $header, $output)) continue;
$parsedArray[$output[1]] = $output[2];
}
Run Code Online (Sandbox Code Playgroud)
ps:未经测试.
- 编辑 -
请享用 ;)
/**
* Parse a set of HTTP headers
*
* @param array The php headers to be parsed
* @param [string] The name of the header to be retrieved
* @return A header value if a header is passed;
* An array with all the headers otherwise
*/
function parseHeaders(array $headers, $header = null)
{
$output = array();
if ('HTTP' === substr($headers[0], 0, 4)) {
list(, $output['status'], $output['status_text']) = explode(' ', $headers[0]);
unset($headers[0]);
}
foreach ($headers as $v) {
$h = preg_split('/:\s*/', $v);
$output[strtolower($h[0])] = $h[1];
}
if (null !== $header) {
if (isset($output[strtolower($header)])) {
return $output[strtolower($header)];
}
return;
}
return $output;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23518 次 |
| 最近记录: |