PHP DOMDocument:替换父元素

时间:2016-11-23 13:05:29

标签: php dom domdocument

请考虑以下代码:

<?php

libxml_use_internal_errors(true);

$exHTML = '
    <div class="container">
        <div class="para">
            Some Text and <strong>HTML</strong>.
        </div>
        <div class="para">
            <div class="match-class another-one">Some text ...</div>
        </div>
        <div class="para">
            Some more Text and <strong>HTML</strong>.
        </div>
    </div>
    <div class="container">
        Another container whose content does not matter ...
    </div>
';

$dom = new DomDocument;
$dom->preserveWhiteSpace = false;

$dom->loadHTML($exHTML);

$finder = new DomXPath($dom);
$paragraphs = $finder->query("//div[@class='container'][1]//div[@class='para']");

foreach($paragraphs as $paragraph) {
    $elements = $finder->query("div[contains(@class, 'match-class another-one')]", $paragraph);

    foreach($elements as $element) {
        $newElement = $dom->createElement('p');
        $newElement->nodeValue = $element->nodeValue;
        $newElement->setAttribute('class', 'newclass');

        $paragraph->replaceChild($newElement, $element);
    }

    echo $dom->saveHTML($paragraph)."\n";
}

最终结果应为:

<p>
    Some Text and <strong>HTML</strong>.
</p>
<p class="newclass">
    Some text ...
</p>
<p>
    Some more Text and <strong>HTML</strong>.
</p>

如何修改和扩展代码以获得所需的结果?任何帮助表示赞赏。 上面公布的代码会产生以下结果:

<div class="para">
    Some Text and <strong>HTML</strong>.
</div>
<div class="para">
    <p class="newclass">Some text ...</p>
</div>
<div class="para">
    Some more Text and <strong>HTML</strong>.
</div>

0 个答案:

没有答案