I’m attempting to pull in an RSS feed, but I only want to show one of the items – a random number – not all of them. I’ve set up a test using a for loop, but can’t seem to get it to work. I come from a JS background. Any help or hints would be much appreciated!
<?php
$url = "http://abc.net.au/bestof/bestofabc.xml";
$rss = simplexml_load_file($url);
if ($rss) {
$items = $rss->channel->item;
for ($i = 0; $i < count($items); $i++){
if ($i == 2) {
echo($items[$i]); // doesn't show anything
}
}
}
?>
You have got basically two options here, for easy of use I assign the item to a variable of its own first:
And then the two options for debugging:
The first line will create a
var_dump, which is PHP and in this case even SimpleXML specific:The second line will create something I bet is common to you, the XML itself:
You did not see any output with:
because that
<item>element does not have a value, but just subelements. For exampleWill output the string:
I hope this is helpful and sheds some light. You find the demo here, it also shows that you can make use of
foreach: