Why does only one (the last) XML file is saved?
I use this below to save me the contents of the XML addresses I ha开发者_Go百科ve in array. However only one XML is saved, specifically the last one. What am I missing here?
$filenames = array('xml url','xml url','xml url');
foreach( $filenames as $filename) {
$xml = simplexml_load_file( $filename );
$xml->asXML("test.xml");
}
You appear to be opening each XML file, then saving them in the same location. File 1 is written, then File 2 overwrites it, then File 3... In short, the last file will overwrite the previous ones, and therefore "only the last one is saved".
What exactly are you trying to do here?
You save them all as the same name, so of course the earlier ones will be lost.
Try this:
$filenames = array('xml url','xml url','xml url');
foreach( $filenames as $key => $filename) {
$xml = simplexml_load_file( $filename );
$xml->asXML('test' . $key. '.xml');
}
That should save the files sequentially as test0.xml
, test1.xml
, test2.xml
and so on.
If you want all your loaded XML URL's to be appended to a single file, you can do something like this:
$filenames = array('xml url','xml url','xml url');
$fullXml = array();
foreach( $filenames as $key => $filename) {
$xml = simplexml_load_file( $filename );
// Convert the simplexml object into a string, and add it to an array
$fullXml[] = $xml->asXML();
}
// Implode the array of all our xml into one big xml string
$fullXml = implode("\n", $fullXml);
// Load the new big xml string into a simplexml object
$xml = simplexml_load_string($fullXml);
// Now we can save the entire xml as your file
$xml->asXml('test.xml');
精彩评论