I am parsing an XML file (source.xml) in PHP and need to identify instances where the <property>
node contains the <rent>
element.
Once identified the entire <property>
parent node for that entry should be copied to a separate XML file (destination.xml).
On completion of the copy that <property>
node should be removed from the source.xml file.
Here is an example of the source.xml file:
<?xml version="1.0" encoding="utf-8"?>
<root>
<property>
...
<rent>
<term>long</term>
<freq>month</freq>
<price_peak>1234</price_peak>
<price_high>1234</price_high>
<price_medium>1234</price_medium>
<price_low>1234</price_low>
</rent>
...
</property>
</root>
I've tried using DOM with the below code however I'm not getting any results at all despite their being hundreds of nodes that match the above requisites. Here is what I have so far:
$destination = new DOMDocument;
$destination->preserveWhiteSpace = true;
$destination->load('destination.xml');
$source = new DOMDocument;
$source->load('source.xml');
$xp = new DOMXPath($source);
foreach ($xp->query('/root/property/rent[term/freq/price_peak/price_high/price_medium/price_low]') as $item) {
$newItem = $destination->documentElement->appendChild(
$destination->createElement('property')
);
foreach (array('term', 'freq', 'price_peak', 'price_high', 'price_medium', 'price_low') as $elementName) {
$newItem->appendChild(
$destination->importNode(
$item->getElementsByTagName($elementName)->property(0),
true
)
);
}
}
$destination->formatOutput = true;
echo $destination->saveXml();
I've only started learning about DOMDocument and it's uses so I'm obviously messing up somewhere so any help is appreciated. Many thanks.