Reading RSS feeds

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
thetinker
Forum Newbie
Posts: 4
Joined: Wed Aug 05, 2009 5:55 am

Reading RSS feeds

Post 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.
User avatar
turbolemon
Forum Commoner
Posts: 70
Joined: Tue Jul 14, 2009 6:45 am
Location: Preston, UK

Re: Reading RSS feeds

Post 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++;
}
thetinker
Forum Newbie
Posts: 4
Joined: Wed Aug 05, 2009 5:55 am

Re: Reading RSS feeds

Post 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
Post Reply