用DOM / Xpath(PHP)重写HTML标签

时间:2012-09-20 19:04:51

标签: php xpath

我在PHP中用DOM / Xpath解析一块HTML。在此HTML中,我想将一些p代码转换为h4代码。

原始HTML =>

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

所需的HTML =&gt;

<h4>Awesome line of text</h4>

如何使用Xpath执行此操作?我想我需要打电话appendChild,但我不确定。感谢您的任何指导。

1 个答案:

答案 0 :(得分: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();
?>