php 如何获取DOMElement节点的html代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12909787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get html code of DOMElement node?
提问by Xaver
I have this html code:
我有这个 html 代码:
<html>
<head>
...
</head>
<body>
<div>
<div class="foo" data-type="bar">
SOMECONTENTWITHMORETAGS
</div>
</div>
</body>
I already can get the "foo" element (but only its content) with this function:
我已经可以使用这个函数获取“foo”元素(但只有它的内容):
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;
}
But I'd like to return all html tags (including its attributes) of DOMElement. How I can do that?
但我想返回 DOMElement 的所有 html 标签(包括它的属性)。我怎么能做到这一点?
回答by lonesomeday
Use the optional argument to DOMDocument::saveHTML: this says "output this element only".
使用可选参数DOMDocument::saveHTML:这表示“仅输出此元素”。
return $node->ownerDocument->saveHTML($node);
Note that the argument is only available from PHP 5.3.6. Before that, you need to use DOMDocument::saveXMLinstead. The results may be slightly different. Also, if you already have a reference to the document, you can just do this:
请注意,该参数仅适用于 PHP 5.3.6。在此之前,您需要改为使用DOMDocument::saveXML。结果可能略有不同。另外,如果您已经有对文档的引用,您可以这样做:
$doc->saveHTML($node);
回答by Saul Martínez
PHP Simple HTML DOM Parsershould do the job!
PHP Simple HTML DOM Parser应该可以完成这项工作!

