Tutorials PHP RSS Parse

RSS Parse

This tutorial will show you how to display a RSS feed on your website.

What is a RSS feed?

RSS stands for Rich Site Summary. It's usually a list of content that would be updated regularly. Users can grab the content without having to visit your site.

Grab the Data

RSS feeds come as XML files. We can use simple xml element to parse out the data.

$xml  = 'http://www.phptrainee.com/rss';
$data = new SimpleXMLElement(file_get_contents($xml));

Looping Through Results

We can use a foreach loop to get through all the data.

foreach($data->channel->item as $content) {
  
  // Create variables
  $title = $content->title;
  $link  = $content->link;
  
  // Print content
  echo '<li><a href="'.$link.'" target="_blank">'.$title.'</a></li>';
}

Limiting the Results

Sometimes you only want to show a couple newest entries. We can set a counter that breaks the loop when it reaches a specified number of entries.

$i = 0;
foreach($data->channel->item as $content) {
  $i++;
  if ($i == 3) {
    break;
  }
}

Final Result

<?php
$xml  = 'http://www.phptrainee.com/rss';
$data = new SimpleXMLElement(file_get_contents($xml));

$i = 0;
foreach($data->channel->item as $content) {
  
  // Create variables
  $title = $content->title;
  $link  = $content->link;
  
  // Print content
  echo '<p><a href="'.$link.'" target="_blank">'.$title.'</a></p>';
  
  // Only show 3 items
  $i++;
  if ($i == 3) {
        break;
    }
}

?>

That's all for this tutorial. See you all next time on PHP Trainee.

Posted by on . Category: PHP


Comments

No comments posted yet

You need to register or login to post new comments.