Page 1 of 1

Reading RSS feeds

Posted: Wed Aug 05, 2009 6:12 am
by thetinker
pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


Hi

I'm new to coding in PHP and need some help with reading a RSS feed and adding it on to my site. i've get this code below and it works fine but it put all of the feed on my page.

My question is - how do i change it so i can only show the first 2 or 3 subjects in the feed on my page?

Code: Select all

<?php   
  
function getFeed($feed_url) {   
      
    $content = file_get_contents($feed_url);   
    $x = new SimpleXmlElement($content);   
       
    echo "<ul>";   
       
    foreach($x->channel->item as $entry) {   
        echo "<li><a href='$entry->link' title='$entry->title'>" . $entry->title . "</a></li>";   
    }   
    echo "</ul>";   
}   
?>

pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.

Re: Reading RSS feeds

Posted: Wed Aug 05, 2009 7:04 am
by turbolemon
You just need to break out of the loop when a condition is met (e.g. the loop number is greater than the limit):

Code: Select all

$i=0;
foreach($x->channel->item as $entry) {
   if ($i<2) break;
   echo "<li><a href='$entry->link' title='$entry->title'>" . $entry->title . "</a></li>"; 
   $i++;
}

Re: Reading RSS feeds

Posted: Wed Aug 05, 2009 8:05 am
by thetinker
Thanks turbolemon

i couldn't get it to work at first but had a play with the code. I had to use this in the end - if ($i==2) break;

If work fine now

Thanks again for you help