jarvis Posted September 1, 2016 Share Posted September 1, 2016 Hi All, I'm hoping someone can help! I've got multiple XML files each start and end with a <property> tag I'm trying to merge all files and the following works in terms of merging the files: #Create an array of all file names $files = array(); #Create a function to combine all XML docs function combineXML($file) { global $xmlstr; $xml = simplexml_load_file($file); foreach($xml as $element) $xmlstr .= $element->asXML(); } #Create an XML file for each result foreach ($posts as $post){ $file_name = $post->vebraid.'.xml'; $myfile = fopen($file_name, "w") or die("Unable to open file!"); $content = $post->xml; fwrite($myfile, $content); #Add filename into array of all file names $path = get_stylesheet_directory_uri(); $directory = '/xml/'; $files[]=$path.$directory.$post->vebraid.'.xml'; #Concatenates two or more XML files by creating a string representation of XML elements then reloading string as XML $xmlstr = '<property>'; foreach ($files as $file) combineXML($file); $xmlstr .= '</property>'; #Convert string to XML for further processing $xml = simplexml_load_string($xmlstr); $bytes = file_put_contents("combined.xml", $xml->asXML()); } However, I need to differentiate between each file within the new combined.xml file, ideally adding <prop_detail> around each merged file, for example: <property> <prop_detail> first file contents </prop_detail> <prop_detail> second file contents </prop_detail> <prop_detail> third file contents </prop_detail> </property> I simply can't see how I can introduce this new element Any help is very much appreciated! Quote Link to comment Share on other sites More sharing options...
cyberRobot Posted September 1, 2016 Share Posted September 1, 2016 Have you tried something like this $xmlstr = '<property>'; foreach ($files as $file) { $xmlstr .= '<prop_detail>'; combineXML($file); $xmlstr .= '</prop_detail>'; } $xmlstr .= '</property>'; Quote Link to comment Share on other sites More sharing options...
Psycho Posted September 1, 2016 Share Posted September 1, 2016 (edited) Just a side note. Using GLOBAL is a bad practice. In this case, it is not even needed. A function should return a value. So, the combineXML() function should look something like this function combineXML($file) { $xml = simplexml_load_file($file); $fileXML = ''; foreach($xml as $element) { $fileXML .= $element->asXML(); } return $fileXML; } Then, in the code cyberRobot posted, change this $xmlstr .= '<prop_detail>'; combineXML($file); $xmlstr .= '</prop_detail>'; To this: $xmlstr .= '<prop_detail>'; $xmlstr .= combineXML($file); $xmlstr .= '</prop_detail>'; Edited September 1, 2016 by Psycho Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.