1

如何从外部网站抓取内容片段并将其显示在我的网站上?(类似于 RSS 提要或其他聚合器所做的事情)。

例如,假设我想显示另一个网站日历中的项目:

其他网站:

<h1>Here's our calendar:</h1>

<div class="calendar_item">
  <h2>Boston Marathon</h2>
  <p class="date">June 23, 2012</p>
  <p class="description">This marathon is 26.2 miles and lots of fun.</p>
</div>

<div class="calendar_item">    
  <h2>Irish Pub Crawl</h2>
  <p class="date">July 17, 2012</p>
  <p class="description">Shamrocks and green things are super-fun.</p>
</div>

<div class="calendar_item">
  <h2>Tim's Birthday</h2>
  <p class="date">August 25, 2012</p>
  <p class="description">It's Tim's birthday, yo.</p>
</div>

我的网站:

<h1>Here's a feed of some calendar items from someone else's website:</h1>

<div class="event_title">Boston Marathon</div>
<div class="event_date">June 23, 2012</div>
<div class="event_description">This marathon is 26.2 miles and lots of fun.</div>

<div class="event_title">Irish Pub Crawl</div>
<div class="event_date">July 17, 2012</div>
<div class="event_description">Shamrocks and green things are super-fun.</div>

<div class="event_title">Tim's Birthday</div>
<div class="event_date">August 25, 2012</div>
<div class="event_description">It's Tim's birthday, yo.</div>

这是我尝试过的(使用 MAMP):

<?php

$url = "http://example.com";

$page = curl($url);

$pattern = '%
<h2>(.+?)</h2>
%i';

preg_match($pattern,$page,$matches);

print_r($matches);

?>

...打印:

Array ( )

教程/等。我查看过包括“尝试 cURL”之类的模棱两可的答案。这看起来很简单,但我是一个难过的菜鸟。

提前谢谢各位:)

4

3 回答 3

3

我不建议使用正则表达式来解析 HTML。PHP 5+ 带有一个解析器,您可以使用它,如下所示。

$content = file_get_contents('test.html');
$doc = 
<<<DOC
$content
DOC;
$dom = new DOMDocument();
$dom->loadHTML($doc);
$h2Tags = $dom->getElementsByTagName("h2");
$pTags = $dom->getElementsByTagName("p");
foreach($h2Tags as $h2 ) {
    //do something
}

foreach($pTags as $p ) {
if($p->getAttribute("class") == "date") {
    //do something
}

}

$h2 是 DOMElement 类型。它继承了 DOMNode。因此,您可以使用 nodeValue 属性来访问这些值。在上面的示例中,您可以编写 $h2->nodeValue 来访问内容。

于 2012-05-07T18:34:47.900 回答
2

你可以试试这个库http://simplehtmldom.sourceforge.net/

然后只是:

foreach($dom->find('p[class=date]' as $p) {
  $date = $p->innertext;
}

这会给你的内容

或者你做的更全球化,用 stripos 深入研究

foreach($dom->find('p') as $p) {
  if(stripos($p->class, 'date') !== false) {
    //do something
  }
}
于 2012-05-07T18:00:27.797 回答
0

这是使用 cURL 的示例:

http://tr2.php.net/manual/en/curl.examples-basic.php

并在申请前检查您是否正在获取数据preg_match。如果你得到了一些,那么正是正则表达式导致了你的问题。

于 2012-05-07T17:58:10.073 回答