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


当前回答

JSON和来自XML的数组分为三行:

$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

大大!

其他回答

不使用正则表达式解析HTML有几个原因。但是,如果您完全控制将生成什么HTML,那么可以使用简单的正则表达式。

上面是一个通过正则表达式解析HTML的函数。请注意,此函数非常敏感,要求HTML遵守某些规则,但它在许多场景中都非常有效。如果您想要一个简单的解析器,并且不想安装库,请尝试一下:

function array_combine_($keys, $values) {
    $result = array();
    foreach ($keys as $i => $k) {
        $result[$k][] = $values[$i];
    }
    array_walk($result, create_function('&$v', '$v = (count($v) == 1)? array_pop($v): $v;'));

    return $result;
}

function extract_data($str) {
    return (is_array($str))
        ? array_map('extract_data', $str)
        : ((!preg_match_all('#<([A-Za-z0-9_]*)[^>]*>(.*?)</\1>#s', $str, $matches))
            ? $str
            : array_map(('extract_data'), array_combine_($matches[1], $matches[2])));
}

print_r(extract_data(file_get_contents("http://www.google.com/")));

我创建了一个名为PHPPowertools/DOM Query的库,它允许您像使用jQuery一样抓取HTML5和XML文档。

在后台,它使用symfony/DomCrawler将CSS选择器转换为XPath选择器。它总是使用相同的DomDocument,即使在将一个对象传递给另一个对象时也是如此,以确保良好的性能。


示例用法:

namespace PowerTools;

// Get file content
$htmlcode = file_get_contents('https://github.com');

// Define your DOMCrawler based on file string
$H = new DOM_Query($htmlcode);

// Define your DOMCrawler based on an existing DOM_Query instance
$H = new DOM_Query($H->select('body'));

// Passing a string (CSS selector)
$s = $H->select('div.foo');

// Passing an element object (DOM Element)
$s = $H->select($documentBody);

// Passing a DOM Query object
$s = $H->select( $H->select('p + p'));

// Select the body tag
$body = $H->select('body');

// Combine different classes as one selector to get all site blocks
$siteblocks = $body->select('.site-header, .masthead, .site-body, .site-footer');

// Nest your methods just like you would with jQuery
$siteblocks->select('button')->add('span')->addClass('icon icon-printer');

// Use a lambda function to set the text of all site blocks
$siteblocks->text(function( $i, $val) {
    return $i . " - " . $val->attr('class');
});

// Append the following HTML to all site blocks
$siteblocks->append('<div class="site-center"></div>');

// Use a descendant selector to select the site's footer
$sitefooter = $body->select('.site-footer > .site-center');

// Set some attributes for the site's footer
$sitefooter->attr(array('id' => 'aweeesome', 'data-val' => 'see'));

// Use a lambda function to set the attributes of all site blocks
$siteblocks->attr('data-val', function( $i, $val) {
    return $i . " - " . $val->attr('class') . " - photo by Kelly Clark";
});

// Select the parent of the site's footer
$sitefooterparent = $sitefooter->parent();

// Remove the class of all i-tags within the site's footer's parent
$sitefooterparent->select('i')->removeAttr('class');

// Wrap the site's footer within two nex selectors
$sitefooter->wrap('<section><div class="footer-wrapper"></div></section>');

[...]

支持的方法:

[x] $(1)[x] $.parseHTML[x] $.parseXML[x] $.parseJSON[x] $选择添加[x] $selection.addClass[x] $selection.after[x] $selection.append[x] $选择属性[x] $选择之前[x] $selection.children[x] $选择最接近[x] $selection.contents[x] $选择分离[x] $selection.每个[x] $selection.eq[x] $selection.empty(2)[x] $selection.find[x] $selection.first[x] $selection.get[x] $selection.insert之后[x] $selection.insertBefore[x] $selection.last[x] $selection.parent[x] $selection.parents[x] $selection.remove[x] $selection.removeAttr[x] $selection.removeClass[x] $selection.text[x] $selection.wrap


出于明显原因,重命名为“select”重命名为“void”,因为“empty”是PHP中的保留字


注:

该库还包括自己的零配置自动加载器,用于PSR-0兼容库。所包含的示例应该可以开箱即用,无需任何额外配置。或者,您可以将其与composer一起使用。

只需使用DOMDocument->loadHTML()就可以了。libxml的HTML解析算法非常好,速度也很快,与流行的观点相反,它不会对格式错误的HTML产生影响。

我们以前已经为我们的需求创建了不少爬虫。最后,通常是简单的正则表达式做得最好。虽然上面列出的库对于创建它们的原因来说是很好的,但如果您知道自己在寻找什么,正则表达式是一种更安全的方法,因为您还可以处理无效的HTML/XTML结构,如果通过大多数解析器加载,则会失败。

XML_HTMLMax相当稳定——即使不再维护它。另一种选择是通过HtmlTidy将HTML导入,然后用标准的XML工具解析它。