← back to code snippets


Fetching data from an RSS feed

Posted on November 12th, 2013 in PHP

Here’s a quick function showing you how to access data from an RSS Feed. This one uses the BBC’s news feed: 

function fetch_news(){

    $data = file_get_contents("http://feeds.bbci.co.uk/news/rss.xml");
    $data = simplexml_load_string($data);
    
    $articles = array();
    
    foreach ($data->channel->item as $item){
    $articles[] = array(
        'title'         => (string)$item->title,
        'description'   => (string) $item->description,
        'link'          => (string)$item->link,
        'date'          => (string)$item->date
    
    );
    
    print_r ($articles);
    }


}
    

All this really does is loop through each item from the RSS (XML) feed, and add each news item (and its data) to an array called $articles. At the end, print_r just dumps our array out on the screen to show what we’ve got.

Source: YouTube