A Simple RSS Reader with SimpleXML

Devolio

Search

What I'm Doing

    Monday, January 28. 2008

    A Simple RSS Reader with SimpleXML

    SimpleXML is exactly that: a simple way to handle XML data (including RSS feeds) with PHP5. Today we'll look at using SimpleXML to read and display RSS 1.0 feeds. We'll start by breaking down what information exactly we want to get from our XML file.
    First off, we need to know the location of the XML file, and load it with SimpleXML. We can do that by providing our feed URL and then giving it to SimpleXML. In this example, I'm going to use the feed for Devolio.
    $feed = "http://devolio.com/blog/feeds/index.rss";
    @simplexml_load_file($feed);

    Note that we're suppressing errors by using the (@), just in case the file we're looking for can't be loaded. Now, the first thing we're going to want to grab from our XML file is the title, URL, and description of the feed. If we look at our XML file, we see the following:
    < channel>
    < title>Devolio< /title>
    < link>http://devolio.com/blog/< /link>
    < description>News, resources, tips and tricks for Web Developers and Freelancers.< /description>

    All of the information we want to get is inside of the channel, so we'll use $rss->channel[0]->name[0] to get what we want.
    $title = $rss->channel[0]->title[0];
    $url = $rss->channel[0]->link[0];
    $desc = $rss->channel[0]->description[0];

    Next thing we're going to do is limit how many results we want back from the feed, I'm going to use 10.
    $entries = 10;

    If we take a look at our XML file again, we'll see that each entry is laid out like so:
    < item>
    < title>Hassle-Free PDF Text Extraction< /title>
    < link>http://devolio.com/blog/archives/273-Hassle-Free-PDF-Text-Extraction.html< /link>
    < description>
    desc...
    < /description>
    < /item>

    This time, each item in the channel will contain it's own title, link, and description. By looping through the items, we can grab as many as we need with $rss->channel[0]->item[$c]->name[0]
    $xtitle = $rss->channel[0]->item[$c]->title[0];
    $xurl = $rss->channel[0]->item[$c]->link[0];
    $xdesc = $rss->channel[0]->item[$c]->description[0];

    Now if we put it all together with a few comments, we have a simple 25 line RSS reader. You can download the code for this tutorial or learn more about SimpleXML. Used a different XML parser? Let us know what you used and how well it worked out for you.

    Trackbacks

    No Trackbacks

    Comments
    Display comments as (Linear | Threaded)

    No comments


    Add Comment

    Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
    Standard emoticons like :-) and ;-) are converted to images.
    E-Mail addresses will not be displayed and will only be used for E-Mail notifications