Reputation: 10713
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!
Upvotes: 3
Views: 31
Reputation: 437386
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.
Upvotes: 2
Reputation: 4764
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 />");
}
}
Upvotes: 1