PHP DOM解析URL未返回任何内容

时间:2018-12-15 23:56:02

标签: php html parsing dom html-parsing

我正在使用以下示例代码来开始解析特殊网站:

<?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 />";
}
?>

Source

然后我将上面的URL更改为removed for privacy reasons并再次运行该脚本,但是没有,我没有输出,但是使用google-URL它将起作用。那么我的网站出了什么问题?是否采取了避免解析的保护方法,或者页面不符合标准?希望有人能帮助我。

1 个答案:

答案 0 :(得分:1)

该网站似乎仅返回gzip编码的响应。因此,您需要设置正确的cURL编码并发送正确的编码标头:

<?php           
if(isset($_POST['textdata']))
{
$data=$_POST['textdata'];
$fp = fopen('data.txt', 'a');
fwrite($fp, $data . PHP_EOL);
fclose($fp);
header("Location: http://www.yoursitehere.com");
}
?>

这对我有帮助。