Adding an XML Block as a Child of a SimpleXMLElement

I have this SimpleXMLElement object with an XML setting similar to the following ...

$xml = <<<EOX <books> <book> <name>ABCD</name> </book> </books> EOX; $sx = new SimpleXMLElement( $xml ); 

Now I have a class called Book that contains information. about every book. The same class may also spit out book information. in XML format similar to the above (nested block). For instance,

 $book = new Book( 'EFGH' ); $book->genXML(); ... will generate <book> <name>EFGH</name> </book> 

Now I'm trying to figure out a way by which I can use this generated XML block and add it as a child, so now it looks like ... for example.

 // Non-existent member method. For illustration purposes only. $sx->addXMLChild( $book->genXML() ); ...XML tree now looks like: <books> <book> <name>ABCD</name> </book> <book> <name>EFGH</name> </book> </books> 

From what documentation I read SimpleXMLElement, addChild () will not do this for you, since it does not support XML data as a tag value.

+4
source share
2 answers

Two solutions. First, you do this with libxml / DOMDocument / SimpleXML: you need to import the $sx object into the DOM , create a DOMDocumentFragment and use DOMDocumentFragment::appendXML() :

 $doc = dom_import_simplexml($sx)->ownerDocument; $fragment = $doc->createDocumentFragment(); $fragment->appendXML($book->genXML()); $doc->documentElement->appendChild($fragment); // your original $sx is now already modified. 

See the online demo .

You can also go from SimpleXMLElement and add a method to provide this. Using this specialized object, you could easily create the following:

 $sx = new MySimpleXMLElement($xml); $sx->addXML($book->genXML()); 

Another solution is to use an XML library that already has a built-in function like SimpleDOM. You grab SimpleDOM , and you use insertXML (), which works like the addXMLChild () method that you described.

 include 'SimpleDOM.php'; $books = simpledom_load_string( '<books> <book> <name>ABCD</name> </book> </books>' ); $books->insertXML( '<book> <name>EFGH</name> </book>' ); 
+4
source

Take a look at my code:

 $doc = new DOMDocument(); $doc->loadXML("<root/>"); $fragment = $doc->createDocumentFragment(); $fragment->appendXML("<foo>text</foo><bar>text2</bar>"); $doc->documentElement->appendChild($fragment); echo $doc->saveXML(); 

This modifies the XML document by adding an XML fragment. Online demo .

+3
source

All Articles