RSM
RSM

Reputation: 15108

Foreach statement only outputting one record when parsing an XML file

I am trying to parse an XML file so that I get all of the records from the <pid> tags that start with a 'b' as shown:

enter image description here

The link to the xml file is:

http://www.bbc.co.uk/radio1/programmes/schedules/england.xml

And the code I have so far is:

<?php

$xml = simplexml_load_file('http://www.bbc.co.uk/radio1/programmes/schedules/england.xml');
foreach($xml->day>broadcasts->broadcast as $pid){
echo $pid->programme->pid;
}
?>

As far as my knowledge goes, this foreach statement should echo out all of the pid records, where it only does the first one.

Any ideas on where my code is going wrong as to how I make it output all of them?

Upvotes: 1

Views: 825

Answers (2)

Benjamin Dubois
Benjamin Dubois

Reputation: 961

you are iterating over whole xml structure, which contains only one "day" node.

you should position your "cursor" first on the parent of the elements you wish to iterate on :

<?php 

$xml = simplexml_load_file('http://www.bbc.co.uk/radio1/programmes/schedules/england.xml');
$broadcasts = $xml->day->broadcasts;
foreach($broadcasts->broadcast as $bc) {
    echo $bc->programme->pid;
}

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270617

Your loop needs to go one level deeper, since the programme nodes are multiple children of a single broadcast node. You therefore need to loop over all the programme nodes in each broadcast node to echo out their pid

foreach($xml->day>broadcasts->broadcast as $broadcast){

  // Loop over all <programme> contained in each <broadcast>
  foreach ($broadcast->programme as $prog) {
    echo $prog->pid;
  }
}

Upvotes: 2

Related Questions