如何获取DOMElement节点的html代码? [英] How to get html code of DOMElement node?
问题描述
我有这个html代码:
I have this html code:
<html>
<head>
...
</head>
<body>
<div>
<div class="foo" data-type="bar">
SOMECONTENTWITHMORETAGS
</div>
</div>
</body>
我已经可以使用此功能获取foo元素(但只有其内容) p>
I already can get the "foo" element (but only its content) with this function:
private function get_html_from_node($node){
$html = '';
$children = $node->childNodes;
foreach ($children as $child) {
$tmp_doc = new DOMDocument();
$tmp_doc->appendChild($tmp_doc->importNode($child,true));
$html .= $tmp_doc->saveHTML();
}
return $html;
}
但是我想返回所有html标签(包括其属性)一个DOMElement。我可以这么做?
But I'd like to return all html tags (including its attributes) of DOMElement. How I can do that?
推荐答案
使用可选参数 DOMDocument :: saveHTML
:这表示仅输出此元素。
Use the optional argument to DOMDocument::saveHTML
: this says "output this element only".
return $node->ownerDocument->saveHTML($node);
请注意,参数只能从PHP 5.3.6中获得。在此之前,您需要使用 DOMDocument :: saveXML
而不是。结果可能略有不同。另外,如果你已经有了文档的引用,你可以这么做:
Note that the argument is only available from PHP 5.3.6. Before that, you need to use DOMDocument::saveXML
instead. The results may be slightly different. Also, if you already have a reference to the document, you can just do this:
$doc->saveHTML($node);
这篇关于如何获取DOMElement节点的html代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!