I need to update node, from whole node from another document:
Original XML:
<a>
<b>Bat</b>
</a>
The output I want:
<a>
<b>bi</b>
</a>
first attempt: replace with 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: throw a “DOMException” exception with the 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} is 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: throw a “DOMException” exception with the message “Not Found” Error 'in / home / zital / scripts / php / dom.php: 42 Stack trace:
0/home/zital/scripts/php/dom.php(42): DOMNode- > replaceChild ( (DOMElement), (DOMElement))
1 {main} /home/zital/scripts/php/dom.php 42