2012-09-20 31 views
0

我在PHP中用DOM/Xpath解析HTML块。在这个HTML中,有几个p标签,我想转换为h4标签。用DOM/Xpath重写HTML标签(PHP)

原始HTML =>

<p class="archive">Awesome line of text</p> 

所需的HTML =>

<h4>Awesome line of text</h4> 

我怎样才能做到这一点使用XPath?我想我需要拨打appendChild,但我不确定。感谢您的任何指导。

+0

是有效的XML “HTML块”? –

回答

1

东西沿着这些路线应该这样做:

<?php 
$html = <<<END 
<html> 
    <head> 
     <title>Test</title> 
    </head> 
    <body> 
     <p>hi</p> 
     <p class="archive">Awesome line of text</p> 
     <p>bye</p> 
     <p class="archive">Another line of <b>text</b></p> 
     <p>welcome</p> 
     <p class="archive">Another <u>line</u> of <b>text</b></p> 
    </body> 
</html> 
END; 

$doc = new DOMDocument(); 
$doc->loadXML($html); 

$xpath = new DOMXPath($doc); 

// Find the nodes we want to change 
$nodes = $xpath->query("//p[@class = 'archive']"); 

foreach ($nodes as $node) { 
    // Create a new H4 node 
    $h4 = $doc->createElement('h4'); 

    // Move the children of the current node to the new one 
    while ($node->hasChildNodes()) 
     $h4->appendChild($node->firstChild); 

    // Replace the current node with the new 
    $node->parentNode->replaceChild($h4, $node); 
} 

echo $doc->saveXML(); 
?> 
+0

这样做。谢谢肖恩! – rocky