如何解析HTML/XML并从中提取信息?
当前回答
尝试简单HTML DOM解析器。
一个用PHP5+编写的HTMLDOM解析器,可以让您以非常简单的方式操作HTML!需要PHP 5+。支持无效的HTML。使用类似jQuery的选择器在HTML页面上查找标记。从HTML中提取单行内容。下载
注意:顾名思义,它可以用于简单的任务。它使用正则表达式而不是HTML解析器,因此对于更复杂的任务,速度会慢得多。它的大部分代码库是在2008年编写的,此后只做了一些小的改进。它不遵循现代PHP编码标准,将其纳入符合PSR的现代项目将是一个挑战。
示例:
如何获取HTML元素:
// Create DOM from URL or file
$html = file_get_html('http://www.example.com/');
// Find all images
foreach($html->find('img') as $element)
echo $element->src . '<br>';
// Find all links
foreach($html->find('a') as $element)
echo $element->href . '<br>';
如何修改HTML元素:
// Create DOM from string
$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');
$html->find('div', 1)->class = 'bar';
$html->find('div[id=hello]', 0)->innertext = 'foo';
echo $html;
从HTML中提取内容:
// Dump contents (without tags) from HTML
echo file_get_html('http://www.google.com/')->plaintext;
刮削Slashdot:
// Create DOM from URL
$html = file_get_html('http://slashdot.org/');
// Find all article blocks
foreach($html->find('div.article') as $article) {
$item['title'] = $article->find('div.title', 0)->plaintext;
$item['intro'] = $article->find('div.intro', 0)->plaintext;
$item['details'] = $article->find('div.details', 0)->plaintext;
$articles[] = $item;
}
print_r($articles);
其他回答
我创建了一个名为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一起使用。
使用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
QueryPath很好,但要小心“跟踪状态”,因为如果你没有意识到它的含义,这可能意味着你浪费了大量调试时间,试图找出发生了什么以及代码为什么不工作。
这意味着对结果集的每一次调用都会修改对象中的结果集,这与jquery中的每个链接都是一个新的集一样是不可链接的,您有一个单独的集,它是查询的结果,而每个函数调用都会更改该单独的集。
为了获得类似jquery的行为,您需要在执行类似过滤器/修改的操作之前进行分支,这意味着它将更紧密地反映jquery中发生的情况。
$results = qp("div p");
$forename = $results->find("input[name='forename']");
$results现在包含输入的结果集[name='rename']而不是原始查询“div p”。这让我很困惑,我发现QueryPath跟踪过滤器和查找结果,以及修改结果并将其存储在对象中的所有内容。你需要这样做
$forename = $results->branch()->find("input[name='forname']")
那么$results将不会被修改,您可以一次又一次地重用结果集,也许有更多知识的人可以稍微澄清一下,但从我的发现来看,基本上是这样的。
XML_HTMLMax相当稳定——即使不再维护它。另一种选择是通过HtmlTidy将HTML导入,然后用标准的XML工具解析它。
简单HTML DOM是一个很棒的开源解析器:
simplehtmldom.sourceforge
它以面向对象的方式处理DOM元素,新的迭代包含了大量不兼容代码。还有一些很棒的函数,如JavaScript中的“find”函数,它将返回该标记名元素的所有实例。
我已经在许多工具中使用了这个,在许多不同类型的网页上测试了它,我认为它非常有用。
推荐文章
- 如何删除和清除所有的本地存储数据
- Json_encode()转义正斜杠
- 如何在PHP中捕获cURL错误
- 强制打开“另存为…”弹出打开文本链接点击PDF在HTML
- 如何修改标签文本?
- 如何在XSLT中实现if-else语句?
- 如何要求一个分叉与作曲家?
- 在HTML中还有其他有用的空格码吗,比如半空格的 , em-spaces, en-spaces等等?
- 输入触发器按钮单击
- 如何在php中创建可选参数?
- Angular 2模板中的标签是什么意思?
- 在文本文件中创建或写入/追加
- 如何设置身体高度溢出滚动
- 为什么PHP的json_encode函数转换UTF-8字符串为十六进制实体?
- 在输入type="number"时禁用webkit的旋转按钮?