Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: dom replace node by root node from another dom

Tags:

dom

replace

php

i need to update a node, from entire node from other document:

Original XML:

<a>
<b>Bat</b>
</a>

Output i want:

<a>
<b>bi</b>
</a>

first attempt: replace by documentfragment

    $original = "<a>
    <b>Bat</b>
    </a>";
    $replace = "<b>Bi</b>";

    $dom = new DOMDocument('1.0', 'utf-8');
    $dom->loadXML($original);

    $xpath = new DOMXpath($dom);
    $b = $xpath->query('//b')->item(0);

    $fragment = $dom->createDocumentFragment();
    $fragment->appendXML($replace);

    $dom->replaceChild($fragment, $b);

    echo $dom->saveXML();

ERROR:

Fatal error: Uncaught exception 'DOMException' with message 'Not Found Error' in /home/zital/scripts/php/dom.php:17 Stack trace:

0 /home/zital/scripts/php/dom.php(17): DOMNode->replaceChild(Object(DOMDocumentFragment), Object(DOMElement))

1 {main} thrown in /home/zital/scripts/php/dom.php on line 17

second attempt: replace by importing node

$original = "<a>
        <b>Bat</b>
</a>";
$replace = "<b>Bi</b>";

$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadXML($original);

$xpath = new DOMXpath($dom);
$b = $xpath->query('//b')->item(0);

$dom2 = new DOMDocument('1.0', 'utf-8');
$dom2->loadXML($replace);

$replace = $dom2->documentElement;
$replace = $dom->importNode($replace, true);

$dom->replaceChild($replace, $b);

echo $dom->saveXML();

ERROR:

Fatal error: Uncaught exception 'DOMException' with message 'Not Found Error' in /home/zital/scripts/php/dom.php:42 Stack trace:

0 /home/zital/scripts/php/dom.php(42): DOMNode->replaceChild(Object(DOMElement), Object(DOMElement))

1 {main} thrown in /home/zital/scripts/php/dom.php on line 42

like image 843
ZiTAL Avatar asked Nov 09 '22 14:11

ZiTAL


1 Answers

you didn't make one more step to get documentElement

$dom->documentElement->replaceChild($replace, $b);

and the result will be

<?xml version="1.0"?>
<a><b>Bi</b></a>

UPD:

In accordance with quite correct Yoshi comment, it is better to write this in such way

$b->parentNode->replaceChild($replace, $b);
like image 174
splash58 Avatar answered Nov 14 '22 22:11

splash58