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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With