I’m traversing an xml file as below:
<?xml version="1.0" encoding="ISO-8859-1"?>
<wrapper>
<site base="http://www.example1.co.uk/" name="example 1">
<page>page1/</page>
</site>
<site base="http://www.example2.co.uk/" name="example 2">
<page>page2/</page>
</site>
</wrapper>
And my php is this:
xml = simplexml_load_file("siteList.xml");
foreach ($xml->site as $site => $child) {
foreach ($xml->$site->page as $a => $page) {
$endUrl = ($child["base"] . "" . $page);
print_r($endUrl . "<br />");
}
}
This technically works, but returns the following:
http://www.example1.co.uk/page1/
http://www.example2.co.uk/page1/
Instead of:
http://www.example1.co.uk/page1/
http://www.example2.co.uk/page2/
It’s using the page from the previous loop somehow, I cannot work it out :'(
Thanks in advance!
You should be iterating over
$childfor the inner loop, but you are not. To fix it, change thisto this
You could also simplify the outer loop to
foreach ($xml->site as $child)as you don’t care about the key; and if you do this, renaming$childto$sitewould be a logical next step to improve readability.