Shahid H.
Shahid H.

Reputation: 21

Php DOM and Xpath - Replace node but keep children of old node

Consider the following html:

<html>
    <title>Xyz</title>
    <body>
        <div>
            <div class='mycls'>
                <div>1 Books</div>
                <div>2 Papers</div>
                <div>3 Pencils</div>
            </div>
        </div>
    <body>
</html>
$dom = new DOMDocument();
$dom->loadHTML([loaded html of remote url through curl]);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('html/body/div[@class="mycls"]');

till here its working fine, i need to replace the node to get following:

<body>
        <div>
            <span>
                <div>1 Books</div>
                <div>2 Papers</div>
                <div>3 Pencils</div>
            </span>
        </div>
    <body>

Upvotes: 0

Views: 1377

Answers (1)

PeeHaa
PeeHaa

Reputation: 72729

Something like the following should work for you:

$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$oldNode = $xpath->query('//div[@class="mycls"]')->item(0);
$span = $dom->createElement('span');

if ($oldNode->hasChildNodes()) {
    $children = [];
    foreach ($oldNode->childNodes as $child) {
        $children[] = $child;
    }
    foreach ($children as $child) {
        $span->appendChild($child->parentNode->removeChild($child));
    }
}

$oldNode->parentNode->replaceChild($span, $oldNode);

echo htmlspecialchars($dom->saveHTML());

Demo: http://codepad.viper-7.com/WNTrR5

Note that in the demo I also have fixed your HTML which was utterly broken :-)

If you demo is really the HTML you are getting back from the cURL call and you cannot change it (no control over it) you can do:

$libxmlErrors = libxml_use_internal_errors(true); // at the start

and

libxml_use_internal_errors($libxmlErrors); // at the end

To prevent errors popping up

Upvotes: 1

Related Questions