如何在PHP中分析标头

Web*_*net 1 php api curl header

我正在使用a file_get_contents与api进行交互以获取简单的GET请求...但是有时它会抛出表示存在错误的标题.如何获取这些标题并确定是否存在问题?

Joh*_*man 5

Php将设置$ http_response_header,之后file_get_contents包含响应头作为标题行/字符串数组.如果您想要的只是标题响应(并且可能不应该,某些LAMP堆栈仍然没有cURL),则不必使用curl.

$ http_response_header上的文档: http ://php.net/manual/en/reserved.variables.httpresponseheader.php

例:

file_get_contents('http://stacksocks.com');

foreach ($http_response_header as $header)
{
    echo $header . "<br>\n";
}
Run Code Online (Sandbox Code Playgroud)

从评论中的帖子中提取的提示:

1)值随每个请求而变化.

2)在方法/函数中使用时,必须将当前值传递给方法/函数.直接在方法/函数中使用$ http_response_header而不通过函数/方法参数赋值将导致错误消息:注意:未定义的变量:http_response_header

3)阵列中的阵列长度和值位置可能会根据被查询的服务器和收到的响应而改变.我不确定阵列中是否存在任何"绝对"值位置.

4)$ http_response_header仅在使用URL而不是本地文件时使用file_get_contents()填充.当提到HTTP_wrapper时,在描述中说明了这一点.