Wordpress development techniques #2 – Fetching RSS feeds with wordpress

Fetching RSS feedsAs promised last week, this week we are looking at fetching RSS feeds with Magpie RSS.

Magpie is an PHP based RSS feed parser; I.E. It fetches RSS feeds to display in other places, which gives it many uses.

Unknown to many, wordpress has the magpie RSS parser built in, this article will teach you how to use it, and also how to fetch and show someones del.icio.us bookmarks!

Fetching feeds in wordpress

Wordpress contains two functions for fetching feeds:

  1. fetch_rss -This function fetches and parses an RSS feed.
  2. wp_rss – This function fetches and parses an RSS feed, then displays the results in an unordered list.

These functions use magpie for parsing the RSS, and Snoopy for retrieving the RSS.

Uses the MagpieRSS and RSSCache (http://magpierss.sourceforge.net/) functions for parsing and automatic caching and the Snoopy HTTP client (http://sourceforge.net/projects/snoopy/) for the actual retrieval.


Including Magpie in a template or plug in

Magpie RSS is built into wordpress’ rss-functions.php file (or rss.php in newer versions). It contains the functions needed to fetch feeds, so it needs to first be included:

1
2
// Include the RSS functions. Older versions of wordpress could use include_once (ABSPATH . WPINC . '/rss-functions.php') or include_once (ABSPATH . WPINC . '/rss.php');;
include_once(ABSPATH . WPINC . '/rss-functions.php');

Fetching the feed with fetch_rss

Next lets tell wordpress what feed we want to parse, and put it to work! If you want to get the results and output them yourself, use fetch_rss.

1
2
// Fetch a feed
$feed = fetch_rss("http://yourfeedaddress");

To limit you results you can slice the array of results:

1
$items = array_slice($feed->items, 0, $maxitems);

After that, use a loop to go through the array contents and output the results (see the del.icio.us bookmarks example further down for more detail on this).

Fetching the feed with wp_rss

If you want to output the results in an unordered list right away, use wp_rss.

1
2
// Fetch a feed, replace $limit with the max results you want
wp_rss("http://yourfeedaddress", $limit);

Example output

The below example shows output from my bookmarks feed using wp_rss.

include_once(ABSPATH . WPINC . ‘/rss-functions.php’);
wp_rss(‘http://del.icio.us/rss/mikejolley’, 5);

Fetching del.icio.us bookmarks – example

The following code gets my last 5 del.icio.us bookmarks, and outputs them to the page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
	// Include the RSS functions of wordpress
	include_once(ABSPATH . WPINC . '/rss-functions.php')
	// Grab my RSS feed
	$feed = fetch_rss("http://del.icio.us/rss/mikejolley");
        // I want 5 results please
	$maxitems = 5;
	$items = array_slice($feed->items, 0, $maxitems);
        // Output the results!
	if(!empty($items)) {
		echo '<ul>';
		foreach ($items as $item) {
			echo '<li>';
			echo '<a href="';
                        // This is a bit messy, but it makes the output valid XHTML strict by removing ampersands
			$item['link'] = str_replace("&", "&amp;", $item['link']);
			$item['link'] = str_replace("&amp;&amp;", "&amp;", $item['link']);
                        // End of messyness. Output the link
			echo $item['link'];
			echo '">';
                        // Output the title
			echo $item['title'];
			echo '</a>';
                        // If i've written a description, output it
			if (isset($item['description'])) {
			        echo '<br />';
				echo $item['description'];
			}
			echo '</li>';
		}
		echo '</ul>';
	}
?>

Neat huh? See what it outputs below:

$feed = fetch_rss(“http://del.icio.us/rss/mikejolley”);
$maxitems = 5;
$items = array_slice($feed->items, 0, $maxitems);
if(!empty($items)) {
echo ‘

That line of code simply sets the output of the fetched feed to be in UTF-8 encoding. Handy.

More about wordpress rss functions


Found this post useful? Why not buy me a coffee!

Related Entries

12 Responses to “Wordpress development techniques #2 – Fetching RSS feeds with wordpress”

RSS feed for comments on this post.

  1. Vincent says:

    Do I still need to install the feedList 2.2 plugin? Or does Magpie handle my cache in the database?

    The last time I used feeds it caused a long load e.g. see the feeds behind the links on this page: http://www.bangkoktalk.nl/?page_id=29 (old wp version)

    Would be nice just to handy my feeds like you described

    Where to place:

    1 define(“MAGPIE_OUTPUT_ENCODING”, “UTF-8″);

    Great post!

    Comment made on July 2, 2007 at 12:45 am

  2. Mike Jolley says:

    Well, both sections say, and I quote:

    Retrieves an RSS feed and parses it, then displays it as an unordered list of links. Uses the MagpieRSS and RSSCache (http://magpierss.sourceforge.net/) functions for parsing and automatic caching and the Snoopy HTTP client (http://sourceforge.net/projects/snoopy/) for the actual retrieval.

    So Its automatic.

    Stick the define line just before the fetch_rss line.

    Comment made on July 2, 2007 at 6:19 am

  3. Jenny says:

    I am totally lost. But I wanna figure this out. I really do.

    Comment made on July 16, 2007 at 5:18 pm

  4. Mark says:

    Hey, man. I love your site. I use it all the time to make sure I’m coding stuff right. :]

    Comment made on August 3, 2007 at 2:02 am

  5. Lakshmi Mareddy says:

    Pretty cool Mike! or should I say “Jolley Good”… I had played with Magpie separately long back, but didnt know it was built-in in WP. Now after reading your article, my mind is racing… A big THANK YOU to you for coming up with this…

    Comment made on September 22, 2007 at 10:52 pm

  6. Christopher Miles says:

    Thanks a lot for this post; I’m now using the native RSS fetcher in Wordpress to create a blogroll on my site using del.icio.us links, and a current and recent reading list from my Google Library RSS feed

    I’m spending half my waking day thinking of new and fiendish ways of parsing RSS feeds to my site now!

    (“Half my waking day” and “fiendish” are probably overstating it a bit.)

    Comment made on November 20, 2007 at 2:38 pm

  7. Mark says:

    Your lesson is similar to one I found on the wordpress codex but yours is more detailed. I have one question: Do you know if there is a way to display/echo the pubdate for each item? I have not been able to figure that out.

    Thanks!

    Comment made on December 14, 2007 at 11:07 pm

  8. Steve says:

    Is it just me, or does anyone else see, “Warning: array_slice() [function.array-slice]: The first argument should be an array in /home/sites/blue-anvil.com/public_html/wp-content/plugins/phpexec.php(41) : eval()’d code on line 4″, in the example boxes? The only reason I ask, is because I am getting this error too, when I try to parse a feed from my own website. It works the first time, but then on refresh it dies and give me a similar error.

    Comment made on May 7, 2008 at 4:59 pm

  9. Jamie says:

    How can I add things like author and date? I’ve tried things like:

    echo $item['dc:publisher'];

    echo $item['pubdate'];

    Unsuccessfully.

    Comment made on May 12, 2008 at 9:46 pm

  10. Mike Jolley says:

    Not sure why there are errors…maybe wordpress team changed something. There is a new function called get_rss however. Maybe that will work.

    Comment made on May 13, 2008 at 11:24 am

  11. bamajr says:

    There was an article which caught my attention on MSN about Facebook. (See it by clicking here)

    This article was written by a writer for PCWorld and posted on the PCWorld site. (See it by clicking here)

    This article was pulled by MSN and displayed as a post to their tech site.

    Credit was given to the PCWorld Writer, but it was posted as a new article on MSN.

    This is what I’m trying to do. I want to pull related tech articles from places like PCWorld and put them on my site as a new blog article (Of course, credit would be given to the original writer!)

    How is this done?

    Comment made on May 21, 2009 at 3:40 pm

The comments are closed.

About this site

Blue Anvil is the online web design journal & portfolio of , a web designer from Norfolk, England. Read More »
ThemeSlice
  • Featured work - More

    • Beefjack
    • Integrity
    • theotaku.com
    • Manic Melon
  • Latest Tweet - More

    • For those planning on upgrading download monitor; backup first. The upgrade script should work in most cases but be sensible.
  • Out of the blue - More

    • Switched: From Shared to VPS

      It’s been about two weeks now since I made the transition from a shared reseller hosting account to a VPS (Virtual Private Server) account – impressions so far, excellent performance but fiddly to configure.

      The reason I wanted to change from shared hosting was the fact the server was always being hacked (even though ALL my scripts were secure), there was frequent downtime, support blamed me for problems every time, and it was slow as hell.

      Those used to a shared hosting environment would probably not know where to start when faced with configuring a VPS. Luckily, a lot of it was pre-configured when I received my account – certainly some of the major security holes were patched. I was not satisfied with those however. As a victim of hacking in the past (previous host swears it was not there fault, something I don’t believe) I took extra care to secure it as a much I could – configuring brute force detection, the firewall, installing mod security (excellent rules for that here: http://www.atomicorp.com/wiki/index.php/Atomic_ModSecurity_Rules) and going though multiple guides (like this one: http://www.webhostingtalk.com/showthread.php?t=468168) with a fine-tooth comb.

      The result? My pages are loading at least 6 times faster, I have had no down time (or at least have not noticed any), and I feel in control and happy. No longer am I at the mercy of shared hosts :)

      If your interested, I chose ServInt as my provider as they offered a great deal, as well as being a managed service (so I’m not on my own if I screw things up). I was tempted by the bells and whistles of Media Temple, but felt the ServInt service was better value.

    • Download Monitor 3.2.2 Maintenance Release

      Download Monitor has received some more love and has been updated. Here’s the change log from the new version:

      • Small bugfix in uploader.php – cat ID
      • Changed stats graph calculation – thanks lggemini
      • Changes to headers in download.php to avoid caching
      • File Browser fixes – $root was clashing with something….
      • exclude_cat works in all sections of download_page now
      • Removed hardcoding of /uploads/
      • Added action to download.php – should be able to use it to stop a download if you want – maybe limiting downloads per day or something? Whatever you want…
      • Made it so if you post new file on ‘edit’ screen, the post date is updated.
      • Fixed the ‘blank meta’ section which blanks out custom field values when nothing is set.
      • Moved ‘allow_url_fopen’ check.
      • Someone said downloads don’t work with spaces in the name. They do! Wasting my time sonny…
      • All work and no play make jolley a dull boy
      • Had to rename capabilities so they work. Apologies if you have to set this up again! Cheers to Mark Dingemanse.
      • {category_ID} custom format tag added. Useful if you want to send someone to its category on the DL page I guess. Also added {category_other} so when no category is set “other” is shown – this is because the download page can show an ‘other’ section if you want it to.
      • You can now manually edit the post date on the edit download screen.

      If you have edited capabilities for download monitor user permissions, you’ll have to again sorry! This is because I named them too long. Also, you should check your forced downloads still work because there was a logic error meaning they may not have been forced after-all…

      Enjoy.

    • Mahousive update to Download Monitor (3.2)

      Today I completed the update for the Wordpress Download Monitor Plugin – many tweaks, fixes, and features added. There were no changes to the database structure so people upgrading should be fine. Here is the list from the change log:

      • {user} tag added for custom formats
      • ‘autop’ option fix
      • Download page buttons applied with CSS so they are easier to customise/translate.
      • Fix for pagination bug after editing a download
      • Category output fix on edit downloads screen
      • Category urls on download page use ID rather than name to prevent errors when cats have the same names.
      • exclude_cat added to download_page shortcode
      • Localised ‘hits’ ‘date’ ‘title’ on download page
      • Option to disable the download logging
      • Read file ‘chunked’ some people found large files were corrupted so this should help (fingers crossed)
      • Added show_tags option to download page – displays x amount of tags on the download page.
      • File Browser root setting and download.php logic/mime types modified thanks to Jim Isaacs (jidd.jimisaacs.com)
      • Interface Improvements
      • Bulk edit categories, custom fields, tags, member only downloads
      • Added roles for download monitor admin – should be able to use with a role manager plugin if you want anyone other than admin to access the admin section e.g. http://wordpress.org/extend/plugins/capsman/
      • Change redirect after add
      • Edit Cat names/parents
      • Dedicated tags and thumbnails fields (they still use meta table though)

      And yes, those category link bugs are fixed at long last, and you can edit category names finally. Phew!

    • Wordpress Spam Stopper Plugin Updated

      Spam stopper has been updated to v3.1 – and most of it has been recoded. Here’s the full list of changes:

      • Added changelog to readme.
      • Email validation bug squashed
      • Cached comments now work; if user forgets to fill in antispam or makes a mistake (and the JS does not catch it) the users comment will not be lost.
      • Redone entire code to make it more efficient
      • Admin section added for changing the antispam question
      • Form ID and honeypot trap added to form
      • Fully localized

      You can get the plugin from wordpress.org: http://wordpress.org/extend/plugins/spam-stopper/

      For support, please keep my comments clean and post on either the wordpress forums or my forum.

      To help support spam-stopper you can make a donation (buy me a coffee, or several) or rate it on wordpress.org. Thanks!