PHP中通过SimpleXMLElement配合DOMDocument提取XML中的HTML内容

PHP中的simplexml_load_file在解析标准XML时没问题, 但是有两点缺陷: 1. 默认会忽略CDATA的内容 2. 所有HTML标签会被忽略, 在上级节点中能看到, 但是无法通过xpath检索 第一点可以通过设置simplexml_load_file的LIBXML_NOCDATA来解决 第二点无法直接解决, 只能通过其他办法, 将HTML节点提取出后, 使用DOMDocument来抽取所要的内容. 相关代码例子如下:

$xml = simplexml_load_file("embeded_html.xml", null, LIBXML_NOCDATA);
$node = $xml->xpath("/PathToHere/ContentItem/DataContent");
$children = $node[0]->children();
$html = $children->asXML();
//print_r($html);
$dom = new DOMDocument;
$dom->loadHTML($html);
//get content
$items = $dom->getElementsByTagName('div');

foreach ($items as $item) {
	if ($item->getAttribute('class') == 'content-attr') {
		echo $item->nodeValue, PHP_EOL;
	}
}

补充: 后来对方技术又提供了另一种解决的方案:

print_r($xml->NewsItem->NewsComponent->ContentItem->DataContent->html->body);
print_r($xml->NewsItem->NewsComponent->ContentItem->DataContent->html->body->div[1]);


The method simplexml_load_file works well with standard XML but: 1. By default, it ignores all CDATA content 2. All HTML content will be skipped. The content exists in the upper nodes, but can not be searched by xpath('path') The first one can be solved by specifying LIBXML_NOCDATA The second one can be solved by using DOMDocument to walk around. The source code:

$xml = simplexml_load_file("embeded_html.xml", null, LIBXML_NOCDATA);
$node = $xml->xpath("/PathToHere/ContentItem/DataContent");
$children = $node[0]->children();
$html = $children->asXML();
//print_r($html);
$dom = new DOMDocument;
$dom->loadHTML($html);
//get content
$items = $dom->getElementsByTagName('div');

foreach ($items as $item) {
	if ($item->getAttribute('class') == 'content-attr') {
		echo $item->nodeValue, PHP_EOL;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值