如何解析HTML/XML并从中提取信息?
当前回答
我已经编写了一个通用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
其他回答
是的,您可以使用simple_html_dom。然而,我已经使用simple_html_dom做了很多工作,特别是在web抓取方面,发现它太脆弱了。它做了基本的工作,但无论如何我都不推荐它。
我从未使用过卷发,但我学到的是,卷发可以更有效地完成这项工作,而且更结实。
请查看此链接:使用curl刮取网站
不使用正则表达式解析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一起使用。
您可以尝试使用类似HTMLTidy的东西来清理任何“损坏”的HTML,并将HTML转换为XHTML,然后可以使用XML解析器解析。
简单HTML DOM是一个很棒的开源解析器:
simplehtmldom.sourceforge
它以面向对象的方式处理DOM元素,新的迭代包含了大量不兼容代码。还有一些很棒的函数,如JavaScript中的“find”函数,它将返回该标记名元素的所有实例。
我已经在许多工具中使用了这个,在许多不同类型的网页上测试了它,我认为它非常有用。
推荐文章
- 如何使Bootstrap 4卡在卡列相同的高度?
- 使用域集图例引导
- 音频停止功能
- 如何禁用谷歌翻译从HTML在Chrome
- 如何将XML转换成PHP数组?
- 向HTML表中添加水平滚动条
- XMLHttpRequest Origin null不允许Access-Control-Allow-Origin for file:/// to file:///(无服务器)
- 在notepad++中格式化代码
- 表单中包含表单,可以吗?
- 如何创建表只使用<div>标签和Css
- html5 - canvas元素-多层
- 如何将对象转换为数组?
- 如何确保<select>表单字段被禁用时提交?
- 如何在HTML文本换行?
- 从IP地址获取位置