如何解析HTML/XML并从中提取信息?


当前回答

简单HTML DOM是一个很棒的开源解析器:

simplehtmldom.sourceforge

它以面向对象的方式处理DOM元素,新的迭代包含了大量不兼容代码。还有一些很棒的函数,如JavaScript中的“find”函数,它将返回该标记名元素的所有实例。

我已经在许多工具中使用了这个,在许多不同类型的网页上测试了它,我认为它非常有用。

其他回答

您可以尝试的另一个选项是QueryPath。它的灵感来自jQuery,但在服务器上使用PHP,并在Drupal中使用。

我推荐PHP简单HTML DOM解析器。

它确实有很好的功能,比如:

foreach($html->find('img') as $element)
       echo $element->src . '<br>';

我已经编写了一个通用XML解析器,可以轻松处理GB文件。它基于XMLReader,非常容易使用:

$source = new XmlExtractor("path/to/tag", "/path/to/file.xml");
foreach ($source as $tag) {
    echo $tag->field1;
    echo $tag->field2->subfield1;
}

下面是github repo:XmlExtractor

如果您熟悉jQuery选择器,可以使用ScarletsQuery for PHP

<pre><?php
include "ScarletsQuery.php";

// Load the HTML content and parse it
$html = file_get_contents('https://www.lipsum.com');
$dom = Scarlets\Library\MarkupLanguage::parseText($html);

// Select meta tag on the HTML header
$description = $dom->selector('head meta[name="description"]')[0];

// Get 'content' attribute value from meta tag
print_r($description->attr('content'));

$description = $dom->selector('#Content p');

// Get element array
print_r($description->view);

这个库通常需要不到1秒的时间来处理脱机html。它还接受无效的HTML或标记属性上缺少引号。

解析xml的最佳方法:

$xml='http://www.example.com/rss.xml';
$rss = simplexml_load_string($xml);
$i = 0;
foreach ($rss->channel->item as $feedItem) {
  $i++;
  echo $title=$feedItem->title;
  echo '<br>';
  echo $link=$feedItem->link;
  echo '<br>';
  if($feedItem->description !='') {
    $des=$feedItem->description;
  } else {
    $des='';
  }
  echo $des;
  echo '<br>';
  if($i>5) break;
}