php - PHP DOM 解析 URL 没有返回任何内容
问题描述
我使用这个示例代码开始解析一个特殊的网站:
<?php
# Use the Curl extension to query Google and get back a page of results
$url = "http://www.google.com";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$html = curl_exec($ch);
curl_close($ch);
# Create a DOM parser object
$dom = new DOMDocument();
# Parse the HTML from Google.
# The @ before the method call suppresses any warnings that
# loadHTML might throw because of invalid HTML in the page.
@$dom->loadHTML($html);
# Iterate over all the <a> tags
foreach($dom->getElementsByTagName('a') as $link) {
# Show the <a href>
echo $link->getAttribute('href');
echo "<br />";
}
?>
然后我将上面的 url 更改为removed for privacy reasons
并再次运行脚本,但不,我没有输出,但使用 google-URL 它将工作。那么我的网站有什么问题呢?是避免解析的保护方法还是页面不符合标准?希望有人可以帮助我。
解决方案
看起来该站点仅返回 gzip 编码的响应。所以你需要设置正确的 cURL 编码并发送正确的编码头:
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_ENCODING , "gzip");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept-Encoding: gzip, deflate, br',
));
$html = curl_exec($ch);
curl_close($ch);
这对我有用。
推荐阅读
- apache-nifi - Nifi 在从 oracle 数据库读取时附加了额外的字符
- java - 从 POST 请求中检索数据时出错
- mongodb - “没有反应堆在运行,必须从 Tokio 1.x 运行时的上下文中调用”当将 mongodb 2 与 actix-web 3 一起使用时
- excel - Excel VBA - Financial Model Color Formatting
- kubernetes - 如何识别 statefulset 中不健康的 pod
- matrix - 在 Julia 中将元组向量转换为矩阵
- google-cloud-platform - 谷歌云计费帐户的问题
- javascript - 与 www 崩溃的 http 请求
- python - 如果 Internet 出现故障,Colab 笔记本执行将失败。如何防止这种情况?
- javascript - 如何使用上下文桥将类传递给渲染器进程