2010-01-18 83 views

回答

118

Compare該更新的變種與PHP Manual User Note #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); 
} 
?> 
+0

謝謝。它工作正常。不應該$ dom-> preserveWhiteSpace = false;在文件加載之前? – JohnM2 2010-01-18 18:59:23

+0

@ JohnM2:[是的,應該](http://stackoverflow.com/questions/798967/php-simplexml-how-to-save-the-file-in-a-formatted-way)。 – hakre 2013-06-23 18:35:31

+0

附加說明:自PHP 5.3.6開始,您可以省去臨時的'DOMDocument'。還有人可能想用'ltrim'替換'trim'(甚至完全刪除它)以保留一些空白,如分行符。 – hakre 2013-06-23 22:01:54

3
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); 
    } 
} 
6

要返回元素的html,您可以使用C14N()

$dom = new DOMDocument(); 
$dom->loadHtml($html); 
$x = new DOMXpath($dom); 
foreach($x->query('//table') as $table){ 
    echo $table->C14N(); 
} 
+2

C14N將嘗試將HTML轉換爲有效的XML。例如
將變爲

ajaybc 2016-05-18 04:05:54

+0

這是一種甩掉元素的HTML的骯髒方式,無需使用saveHTML來輸出html,head和body標籤。 – 2016-05-18 14:53:26

3

簡化哈伊姆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> 
*/ 

有沒有必要設置preserveWhiteSpaceformatOutput

14

這裏是一個函數式編程風格版本:

function innerHTML($node) { 
    return implode(array_map([$node->ownerDocument,"saveHTML"], 
          iterator_to_array($node->childNodes))); 
} 
4

除了trincot的漂亮版本array_mapimplode但這次array_reduce

return array_reduce(
    iterator_to_array($node->childNodes), 
    function ($carry, \DOMNode $child) { 
     return $carry.$child->ownerDocument->saveHTML($child); 
    } 
); 

仍然不理解,爲什麼沒有reduce()方法接受數組和迭代器。