Error message

The spam filter installed on this site is currently unavailable. Per site policy, we are unable to accept new submissions until that problem is resolved. Please try resubmitting the form in a couple of minutes.

Drupal - Render an RSS Feed with PHP

Category: 

Sometimes you want to show the output of an RSS feed somewhere in your Drupal site. Well with this handy dandy function, we can do just that:

/**
 * Given an RSS url, and an associative array of options, this function will
 * return a rendered RSS feed. Options:
 *    item_count => how many items to return (defaults to 5)
 *    characters => how many characters to render in an item
 *      0 = unlimited
 *      200 = default
 */

function my_module_render_rss_feed($feed_url, $options = array()) {

  $html = '';

  // Setup default options.
  if (!isset($options['item_count'])) { $options['item_count'] = 5; }
  if (!isset($options['characters'])) { $options['characters'] = 200; }

  // Initiate curl. 
  $curl = curl_init(); 

  // Setup curl. 
  curl_setopt($curl, CURLOPT_URL,"$feed_url"); 
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
  curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0); 

  // Grab the xml.
  $xml_file = curl_exec($curl);

  // Close curl.
  curl_close($curl);

  // Get the xml string.
  $xml = simplexml_load_string($xml_file);

  // For each rss item.
  foreach ($xml->channel->item as $item) {
    $description = strip_tags($item->description);
    if ($options['characters'] != 0) { $description = substr($description, 0, $options['characters']) . '...'; }
    if ($options['item_count'] > 0) { 
      $html .= "<div class='my_module_rss_item'><a href='{$item->link}'>{$item->title}</a><p>$description</p></div>";  
    }
    $options['item_count']--; 
  }

  // Return the rendered rss feed html.
  return '<div class="my_module_rss_wrapper">' . $html . '</div>';
}

Put that function in your .module file and have a wonderful day.

Side note, this function is independant of Drupal, meaning it will work for any PHP site you may have.

Add new comment