PHP XML Traversing go awry

I am viewing the file xml

as shown 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 mine php

:

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:

http://www.example1.co.uk/page1/
http://www.example2.co.uk/page2/

      

It uses somehow page

from the previous loop, I can't handle it: '(

Thanks in advance!

+3


source to share


2 answers


You have to iterate over $child

for the inner loop, but you don't. To fix this, change this

foreach ($xml->$site->page as $a => $page) {

      

to that



foreach ($child as $page) { // you don't even need the $a

      

You can also simplify the outer loop to foreach ($xml->site as $child)

, since you don't need a key; and if you do that, renaming $child

to $site

will be the logical next step to improve readability.

+2


source


Used page

from the previous cycle. Maybe 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 />");
  }
}

      

+1


source







All Articles