我正在用 PHP 中的 DOM/Xpath 解析 HTML 块。在这个 HTML 中,有一些p
标签我想转换为h4
标签。
原始 HTML =>
<p class="archive">Awesome line of text</p>
所需的 HTML =>
<h4>Awesome line of text</h4>
我怎样才能用 Xpath 做到这一点?我想我需要打电话appendChild
,但我不确定。感谢您的任何指导。
沿着这些路线的东西应该这样做:
<?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();
?>