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


当前回答

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

其他回答

Advanced Html Dom是一个简单的Html Dom替代品,它提供了相同的界面,但它是基于Dom的,这意味着不会出现任何相关的内存问题。

它还具有完整的CSS支持,包括jQuery扩展。

使用FluidXML,您可以使用XPath和CSS选择器查询和迭代XML。

$doc = fluidxml('<html>...</html>');

$title = $doc->query('//head/title')[0]->nodeValue;

$doc->query('//body/p', 'div.active', '#bgId')
        ->each(function($i, $node) {
            // $node is a DOMNode.
            $tag   = $node->nodeName;
            $text  = $node->nodeValue;
            $class = $node->getAttribute('class');
        });

https://github.com/servo-php/fluidxml

您可以尝试使用类似HTMLTidy的东西来清理任何“损坏”的HTML,并将HTML转换为XHTML,然后可以使用XML解析器解析。

如果您熟悉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或标记属性上缺少引号。

对于HTML5,html5lib已经被放弃多年了。我能找到的唯一一个最近更新和维护记录的HTML5库是一周多前刚刚发布到beta 1.0的HTML5 php。