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:
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?
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;
}
}
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;
}
精彩评论