如何获得DOMNode的innerHTML?
您在PHP DOM实现中使用了哪个函数来获取DOMNode的innerHTML? 有人能提供可靠的解决scheme
outerHTML当然也会。
将此更新的变体与PHP手动用户说明#89718进行比较 :
<?php function DOMinnerHTML(DOMNode $element) { $innerHTML = ""; $children = $element->childNodes; foreach ($children as $child) { $innerHTML .= $element->ownerDocument->saveHTML($child); } return $innerHTML; } ?>
例:
<?php $dom= new DOMDocument(); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->load($html_string); $domTables = $dom->getElementsByTagName("table"); // Iterate over DOMNodeList (Implements Traversable) foreach ($domTables as $table) { echo DOMinnerHTML($table); } ?>
这是一个函数式编程风格的版本:
function innerHTML($node) { return implode(array_map([$node->ownerDocument,"saveHTML"], iterator_to_array($node->childNodes))); }
要返回元素的html
,可以使用C14N() :
$dom = new DOMDocument(); $dom->loadHtml($html); $x = new DOMXpath($dom); foreach($x->query('//table') as $table){ echo $table->C14N(); }
function setnodevalue($doc, $node, $newvalue){ while($node->childNodes->length> 0){ $node->removeChild($node->firstChild); } $fragment= $doc->createDocumentFragment(); $fragment->preserveWhiteSpace= false; if(!empty($newvalue)){ $fragment->appendXML(trim($newvalue)); $nod= $doc->importNode($fragment, true); $node->appendChild($nod); } }
Haim Evgi的简化版本的答案是:
<?php function innerHTML(\DOMElement $element) { $doc = $element->ownerDocument; $html = ''; foreach ($element->childNodes as $node) { $html .= $doc->saveHTML($node); } return $html; }
用法示例:
<?php $doc = new \DOMDocument(); $doc->loadHTML("<body><div id='foo'><p>This is <b>an <i>example</i></b> paragraph<br>\n\ncontaining newlines.</p><p>This is another paragraph.</p></div></body>"); print innerHTML($doc->getElementById('foo')); /* <p>This is <b>an <i>example</i></b> paragraph<br> containing newlines.</p> <p>This is another paragraph.</p> */
没有必要设置preserveWhiteSpace
或formatOutput
。
除了trincot与array_map
和implode
的漂亮版本,这次还有array_reduce
:
return array_reduce( iterator_to_array($node->childNodes), function ($carry, \DOMNode $child) { return $carry.$child->ownerDocument->saveHTML($child); } );
仍然不明白,为什么没有reduce()
方法接受数组和迭代器。