如何解析 PHP 中的响应头? [英] How to parse response headers in PHP?
问题描述
我向 REST API 发出了 oauth 签名的请求,并将响应标头放在一个数组中,如下所示:
I have made an oauth signed request to a REST API and have the response headers in an array like so:
[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
我想弄清楚如何解析标头以便轻松检索 HTTP 状态代码、Content-Location、oauth_token 和 oauth_token_secret 等项目?
I am trying to figure out how to parse the headers for easy retrieval of items such as the HTTP status code, Content-Location, oauth_token, and oauth_token_secret?
推荐答案
您需要迭代数组并检查 stripos()
以找到您要查找的标头.在大多数情况下,您然后在 :
上 explode()
(限制为 2 个结果部分),但 HTTP 响应代码将要求您在空格上爆炸.
You'll need to iterate the array and check stripos()
to find the header you're looking for. In most cases, you then explode()
on :
(limiting to 2 resultant parts), but the HTTP response code will require you to explode on the spaces.
// 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/') === 0) {
list(,$code, $status) = explode(' ', $r, 3);
echo "Code: $code, Status: $status";
break;
}
}
这篇关于如何解析 PHP 中的响应头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!