只显示特定的ID与PHP网页抓取


Only show certain ID with PHP web scrape?

我正在做一个个人项目,它获取我当地气象站的学校/企业关闭的内容,并将结果显示在我的个人网站上。由于该站点不使用RSS提要(遗憾的是),我考虑使用PHP抓取来获取页面的内容,但我只想显示某个ID元素。这可能吗?

我的PHP代码是,

<?php
$url = 'http://website.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
?>

我正在考虑使用preg_match,但我不确定语法,或者如果这是正确的命令。我要显示的ID元素是#LeftColumnContent_closings_dg

下面是一个使用DOMDocument的示例。它从第一个具有id="test"…的<h1>元素中提取文本

$html = '
<html>
<body>
<h1 id="test">test element text</h1>
<h1>test two</h1>
</body>
</html>
';
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$res = $xpath->query('//h1[@id="test"]');
if ($res->item(0) !== NULL) {
  $test = $res->item(0)->nodeValue;
}

我使用过的一个库是PHPQuery: http://code.google.com/p/phpquery/.

你基本上把你的网站变成一个字符串(就像你上面那样),然后做:

phpQuery::newDocument($output);
$titleElement = pq('title');
$title = $titleElement->html();
例如,

将获取title元素的内容。这样做的好处是,所有的方法都是以jQuery的名字命名的,如果您已经了解jQuery,那么学习起来非常容易。