wp_remote_retrieve_headers()
云策文档标注
概述
wp_remote_retrieve_headers() 函数用于从 HTTP 响应中提取头部信息,返回一个 WpOrgRequestsUtilityCaseInsensitiveDictionary 实例或数组。它检查响应是否为 WP_Error 或是否包含 headers 键,确保安全处理。
关键要点
- 函数参数:$response(必需),类型为 array 或 WP_Error,表示 HTTP 响应。
- 返回值:WpOrgRequestsUtilityCaseInsensitiveDictionary 或 array,包含响应头部;如果参数无效则返回空数组。
- 版本变更:自 4.6.0 起,返回值从数组改为 WpOrgRequestsUtilityCaseInsensitiveDictionary 实例。
- 相关函数:与 is_wp_error()、wp_get_http_headers() 等配合使用,用于 HTTP 请求处理。
代码示例
// 示例:获取响应头部并访问特定值
$headerResult = wp_remote_retrieve_headers($response);
$contentLength = $headerResult['content-length'];
// 示例:将头部转换为数组并打印
$headerResultForPrint = (array)$headerResult;
print_r($headerResultForPrint);注意事项
- 使用前需确保 $response 参数正确,否则可能返回空数组。
- 从 4.6.0 版本开始,返回值类型变化,需注意兼容性。
- 访问头部值时,可直接使用数组键,但需注意 WpOrgRequestsUtilityCaseInsensitiveDictionary 的实例特性。
原文内容
Retrieves only the headers from the raw response.
Description
See also
- WpOrgRequestsUtilityCaseInsensitiveDictionary
Parameters
$responsearray|WP_Errorrequired-
HTTP response.
Source
function wp_remote_retrieve_headers( $response ) {
if ( is_wp_error( $response ) || ! isset( $response['headers'] ) ) {
return array();
}
return $response['headers'];
}
Skip to note 2 content
vee
The returned value of
wp_remote_retrieve_headers($response)will be something like this…Requests_Utility_CaseInsensitiveDictionary::__set_state(array( 'data' => array ( 'server' => 'nginx/1.10.3 (Ubuntu)', 'date' => 'Wed, 09 Jan 2019 07:25:38 GMT', 'content-type' => 'application/octet-stream', 'content-length' => '1438086', 'last-modified' => 'Tue, 01 May 2018 04:56:08 GMT', 'etag' => '"5ae7f368-15f186"', 'accept-ranges' => 'bytes', ), ))To access only one value:
$headerResult = wp_remote_retrieve_headers($response); $headerResult['content-length'];You can just type in the array key.
To get the whole array:
$headerResult = wp_remote_retrieve_headers($response); $headerResultForPrint = (array)$headerResult; print_r($headerResultForPrint);You have to use type cast
(array).