Skip to content

DOMElement::replaceWith() doesn't replace node with DOMDocumentFragment but just deletes node or causes wrapping <></> depending on libxml2 version #11625

Closed
@fluffycondor

Description

@fluffycondor

Description

The following code:

<?php
$html = <<<HTML
<!DOCTYPE HTML>
<html>
<body>
    <div></div>
</body>
</html>
HTML;

$dom = new DOMDocument();
$dom->loadHTML($html);

$divs = iterator_to_array($dom->getElementsByTagName('div')->getIterator());
foreach ($divs as $div) {
    $fragment = $dom->createDocumentFragment();
    $fragment->appendXML('<p>Hi!</p>');
    $div->replaceWith($fragment);
}

echo $dom->saveHTML();

Resulted in this output:

<!DOCTYPE HTML>
<html>
<body>
    
</body>
</html>

But I expected this output instead:

<!DOCTYPE HTML>
<html>
<body>
    <p>Hi!</p>
</body>
</html>

It works as expected if I replace the line $div->replaceWith($fragment); with $div->replaceWith(...$fragment->childNodes);.

PHP Version

PHP 8.2.8

Operating System

Windows 10 x64.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions