First of all, I need to Find a parent node by a specific child node value in an xml doc; Then copy some specific children nodes from the parent node to another xml doc.
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 the parent node <item>
that has it's child node <isLive>
value set to "1". Then copy other children nodes of the parent node to the destination xml.
e.g. If parent node <item>
has its child node <isLive>
set to 1. Copy <title>
, <rrp>
and <offerPrice>
nodes and their values and add them to the destination file as children nodes as shown above.
Pardon my technical lingo if I have not used them correctly.
Many thanks for the help guys!
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();
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