Note that there are some explanatory texts on larger screens.

plurals
  1. POMultiple PHP foreach loops on XML file retaining data from previous foreach loops
    text
    copied!<p>I'm currently splitting one xml file down into a number of smaller ones using PHP. To do this I'm creating the new xml files from an array of titles, and then using a foreach loop to go through the original xml file, and using if statements to check if the 'subcategory' of each 'product' matches one of the relevant files, and then adding the relevant data within the if statement.</p> <p>My problem is that the first file comes out fine with just the relevant data, but then each one after that has the data from the previous files that have been populated, as well as its own.</p> <p>The code below shows the working here - I currently have separate foreach loops for each subcategory, but from this I have no idea why, for example, the search for subcategory3 would pick up subcategory1, subcategory2 and subcategory3 (although I'm probably missing something fairly obvious!)...</p> <pre><code>foreach( $xml-&gt;product as $product ) { // Look for different subcategories if (strpos($product-&gt;category ,'subcategory1') !== false) { // write data to xml file and save $root = $xmlFile-&gt;createElement("product"); $root = $xmlFile-&gt;appendChild($root); // These lines are repeated for the various nodes $xml_node = $xmlFile-&gt;createElement("node1"); $xml_node = $root-&gt;appendChild($xml_node); $node1Text = $xmlFile-&gt;createTextNode($product-&gt;node1); $node1Text = $xml_node-&gt;appendChild($node1Text); // Re-save the xml file $xmlFile-&gt;save("file.xml"); } } </code></pre> <p>Any help would be much appreciated - thanks in advance guys!</p> <p>Oh and I also briefly tried on foreach loop for a number of subcategories and used if and elseif for the different subcategories, but got the same results..</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload