I want to concatenate two XML files. Not sure what I'm doing wrong.
Using this code I get either
1. error saying that "Cannot add child. Parent is not a permanent member of the XML tree"
This happens when I change line 19 like this:
$rootnode->addChild($availnode);
- XML that looks like this:
Here's the code I'm using:<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?> <AvailableBatch> <Date>10/07/2010</Date> <UDT>1286410501</UDT> <Type>Full</Type> < />< />< />< />< />< /></AvailableBatch>
Contents of stock_001.xml:<?php for($g=1;$g<=2;$g++) { $fileno = sprintf('%03d', $g); if(file_exists("stock_$fileno.xml")) { $stock_files[] = "stock_$fileno.xml"; } } $xmlstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <AvailableBatch> <Date>".date('m/d/Y')."</Date> <UDT>1286410501</UDT> <Type>Full</Type> </AvailableBatch>"; $filename = "stock_001.xml"; // $xmlstring = file_get_contents($filename); $xml = new SimpleXMLElement($xmlstring); $rootnode = $xml->xpath("/AvailableBatch"); foreach($stock_files as $fname) { $xmlstr = file_get_contents($fname); $xml_app = new SimpleXMLElement($xmlstr); $f = $xml_app->xpath("/AvailableBatch/Available"); foreach ($f as $availnode) { $xml->addChild($availnode); } // foreach ($xml_app->AvailableBatch->children() as $availnode) unset($xmlstr); unset($xml_app); } // foreach($stock_files as $fname) echo $xml->asXML(); // file_put_contents("stock.xml", $xml->asXML()); ?>
Contents of stock_002.xml:<?xml version="1.0" encoding="UTF-8"?> <AvailableBatch> <Date>10/06/2010</Date> <UDT>1286410501</UDT> <Type>Full</Type> <Available> <Sku>427890</Sku> <Part>1001BSG</Part> <Qty>109</Qty> <Time>20:18:01</Time> </Available> <Available> <Sku>427870</Sku> <Part>1003BSS</Part> <Qty>110</Qty> <Time>20:18:01</Time> </Available> <Available> <Sku>427730</Sku> <Part>1004BSG</Part> <Qty>98</Qty> <Time>20:18:01</Time> </Available> </AvailableBatch>
<?xml version="1.0" encoding="UTF-8"?> <AvailableBatch> <Available> <Sku>237770</Sku> <Part>AF400MD</Part> <Qty>3</Qty> <Time>20:18:03</Time> </Available> <Available> <Sku>237790</Sku> <Part>AF401LG</Part> <Qty>30</Qty> <Time>20:18:03</Time> </Available> <Available> <Sku>237810</Sku> <Part>AF401MD</Part> <Qty>174</Qty> <Time>20:18:03</Time> </Available> </AvailableBatch>