[英]Why file_get_contents returning garbled data?
我正在尝试使用一些简单的php从下面的页面中获取HTML。
网址: https : //kat.cr/usearch/architecture%20category%3Abooks/
我的代码是:
$html = file_get_contents('https://kat.cr/usearch/architecture%20category%3Abooks/');
echo $html;
在哪里file_get_contents
工作,但返回加扰的数据:
我尝试使用cUrl
以及各种函数,例如: htmlentities(),
mb_convert_encoding
, utf8_encode
等,但只是获得了加扰文本的不同变体。
页面的来源说这是charset=utf-8
,但是我不确定是什么问题。
在基本URL kat.cr
上调用file_get_contents()
kat.cr
返回相同的混乱。
我在这里想念什么?
它是GZ压缩的,当被浏览器获取时,浏览器将其解压缩,因此您需要解压缩。 要输出它,也可以使用readgzfile() :
readgzfile('https://kat.cr/usearch/architecture%20category%3Abooks/');
您的站点响应正在被压缩,因此必须解压缩才能将其转换为原始形式。
最快的方法是使用gzinflate()
,如下所示:
$html = gzinflate(substr(file_get_contents("https://kat.cr/usearch/architecture%20category%3Abooks/"), 10, -8));
或者,对于更高级的解决方案,请考虑以下功能(在此博客中找到):
function get_url($url)
{
//user agent is very necessary, otherwise some websites like google.com wont give zipped content
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-Language: en-US,en;q=0.8rn" .
"Accept-Encoding: gzip,deflate,sdchrn" .
"Accept-Charset:UTF-8,*;q=0.5rn" .
"User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:19.0) Gecko/20100101 Firefox/19.0 FirePHP/0.4rn"
)
);
$context = stream_context_create($opts);
$content = file_get_contents($url ,false,$context);
//If http response header mentions that content is gzipped, then uncompress it
foreach($http_response_header as $c => $h)
{
if(stristr($h, 'content-encoding') and stristr($h, 'gzip'))
{
//Now lets uncompress the compressed data
$content = gzinflate( substr($content,10,-8) );
}
}
return $content;
}
echo get_url('http://www.google.com/');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.