2012-09-20 57 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