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 $child for the inner loop, but you are not. To fix it, change this
foreach ($xml->$site->page as $a => $page) {
to this
foreach ($child as $page) { // you don't even need the $a
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 $child to $site would be a logical next step to improve readability.
It is using the page from the previous loop. Perhaps this change will help:
xml = simplexml_load_file("siteList.xml");
foreach ($xml->site as $site => $child) {
foreach ($site->page as $a => $page) {
$endUrl = ($child["base"] . "" . $page);
print_r($endUrl . "<br />");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With