PHP Copy xml nodes from one document to another

First of all, I need to find the parent node for the specific child node value in the xml document; Then copy some child nodes from the parent node to another xml document.

For instance:

DESTINATION FILE: ('destination.xml') <item> <offerStartDate>2012-15-02</offerStartDate> <offerEndDate>2012-19-02</offerEndDate> <title>Item Title</title> <rrp>14.99</rrp> <offerPrice>9.99</offerPrice> </item> 

and

 SOURCE FILE: ('source.xml') <items> <item> <title>Item A</title> <description>This is the description for Item A</description> <id>1003</id> <price> <rrp>10.00</rrp> <offerPrice>4.99</offerPrice> </price> <offer> <deal> <isLive>0</isLive> </deal> </offer> </item> <item> <title>Item B</title> <description>This is the description for Item B</description> <id>1003</id> <price> <rrp>14.99</rrp> <offerPrice>9.99</offerPrice> </price> <offer> <deal> <isLive>1</isLive> </deal> </offer> </item> <item> <title>Item C</title> <description>This is the description for Item C</description> <id>1003</id> <price> <rrp>9.99</rrp> <offerPrice>5.99</offerPrice> </price> <offer> <deal> <isLive>0</isLive> </deal> </offer> </item> 

I want to find a parent node <item> that has a child value of node <isLive> set to "1". Then copy the other child nodes of the parent node to the destination XML.

eg. If the parent node <item> has its own child node <isLive> set to 1. Copy the nodes and tags <title> , <rrp> and <offerPrice> and add them to the target file as child nodes, as shown above.

Forgive my technical jargon if I did not use them correctly.

Thanks so much for helping the guys!

+4
source share
1 answer

With SimpleXml ( demo ):

 $dItems = simplexml_load_file('destination.xml'); $sItems = simplexml_load_file('source.xml'); foreach ($sItems->xpath('/items/item[offer/deal/isLive=1]') as $item) { $newItem = $dItems->addChild('item'); $newItem->addChild('title', $item->title); $newItem->addChild('rrp', $item->price->rrp); $newItem->addChild('offerprice', $item->price->offerPrice); } echo $dItems->saveXML(); 

With DOM ( demo ):

 $destination = new DOMDocument; $destination->preserveWhiteSpace = false; $destination->load('destination.xml'); $source = new DOMDocument; $source->load('source.xml'); $xp = new DOMXPath($source); foreach ($xp->query('/items/item[offer/deal/isLive=1]') as $item) { $newItem = $destination->documentElement->appendChild( $destination->createElement('item') ); foreach (array('title', 'rrp', 'offerPrice') as $elementName) { $newItem->appendChild( $destination->importNode( $item->getElementsByTagName($elementName)->item(0), true ) ); } } $destination->formatOutput = true; echo $destination->saveXml(); 
+6
source

Source: https://habr.com/ru/post/1396832/


All Articles