Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add SimpleXML node to SimpleXML

Tags:

php

xml

simplexml

I have two SimpleXML objects. How can I add one object as a child element of the other object.

Please note, that this cannot be done with the addChild method, since it would convert the given value to a string before adding.

like image 791
BetaRide Avatar asked Apr 29 '26 16:04

BetaRide


1 Answers

I found that SimpleXML and DOM can be use in parallel on the same data. I had to read through a whole lot of manual pages. After all I found this solution:

$dom_doc = dom_import_simplexml($node1)->ownerDocument;
$dom_node2 = dom_import_simplexml(new SimpleXMLElement($node_str));
$node2 = $dom_doc->importNode($dom_node2, TRUE);
$node_parent = $dom_doc->getElementsByTagName('Name-of-adding-point');
$node_parent->item(0)->appendChild($node2);

What is interesting, that SimpleXML and DOM can be used in parallel on the same data. There's no need to convert forward and bachward all the time. Read http://au.php.net/manual/en/function.dom-import-simplexml.php#89402 for more details about this.

like image 58
BetaRide Avatar answered May 01 '26 04:05

BetaRide



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!