如何解析HTML/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或标记属性上缺少引号。

其他回答

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

XML_HTMLMax相当稳定——即使不再维护它。另一种选择是通过HtmlTidy将HTML导入,然后用标准的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或标记属性上缺少引号。

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

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