调用file_get_contents后,$http_response_header会返回响应头,包括状态码。
Content-Encoding 标头指定使用哪种编码,例如标头Content-Encoding: gzip 将指定内容使用gzip 编码。
所以我会编写一个函数将标头映射到数组header name => value,然后检查Content-Encoding 条目以确定响应是否使用gzip 压缩。
创建从标题名称到值的映射
function transformIntoHeaderMap(array $headers)
{
去掉状态标头(例如HTTP/1.1 200 OK),因为它不适合header name: value 格式。
$headersWithValues = array_filter($headers, function ($header) { return strpos($header, ':') !== false; });
现在在: 处拆分标题并将键和值写入映射。修剪值,以消除开头/结尾处的空格。
$headerMap = [];
foreach ($headersWithValues as $header) {
list($key, $value) = explode(':', $header);
$headerMap[$key] = trim($value);
}
return $headerMap;
}
判断内容是否被压缩
检查header是否设置,然后检查是否有你要找的值(gzip)。
function isGzipHeaderSet(array $headerMap)
{
return isset($headerMap['Content-Encoding']) &&
$headerMap['Content-Encoding'] == 'gzip';
}
解压缩内容(如果已压缩)
$vid = 231231;
$contents = file_get_contents("https://www.thevideositeurl.com/embed/{$vid}/");
if (isGzipHeaderSet(transformIntoHeaderMap($http_response_header))) {
$contents = gzdecode($contents);
}
echo $contents;
替代方案
更简单的方法可能是使用array_search 并直接在$http_response_header 中查找字符串Content-Encoding: gzip。但我认为这种方法对于标题中的空格更加健壮。