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


当前回答

我创建了一个名为HTML5DOMDocument的库,可以在https://github.com/ivopetkov/html5-dom-document-php

它还支持查询选择器,我认为这在您的情况下非常有用。下面是一些示例代码:

$dom = new IvoPetkov\HTML5DOMDocument();
$dom->loadHTML('<!DOCTYPE html><html><body><h1>Hello</h1><div class="content">This is some text</div></body></html>');
echo $dom->querySelector('h1')->innerHTML;

其他回答

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

顺便说一下,这通常被称为屏幕刮擦。我为此使用的库是SimpleHTMLDomParser。

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

SimpleHtmlDom的第三方替代方案使用DOM而不是字符串解析:phpQuery、Zend_DOM、QueryPath和FluentDom。

使用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