首页 > 解决方案 > 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 它将工作。那么我的网站有什么问题呢?是避免解析的保护方法还是页面不符合标准?希望有人可以帮助我。

标签: phphtmlparsingdomhtml-parsing

解决方案


看起来该站点仅返回 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);

这对我有用。


推荐阅读