2011-12-24

Step 1: Use something overly complicated to do something really simple
Step 2: Swear a lot when things don't work the way they should
Step 3: Write something simple to do a simple task
Step 4: Rejoice!
What am I talking about? Let me spin a tale.....

I need to occasionally pull data from an RSS feed and I was hoping to do the data parsing with a web framework module. Unfortunately, the module worked in a less than ideal manner and couldn't parse the targeted RSS feed. The parser kept throwing errors about the feed being poorly formatted, however, all of my testing confirmed that the feed was properly formatted. Time to write some code!

In order to solve my problem, I first wrote a very basic bit of code to do the following:

  1. create a DOM document
  2. load the RSS feed into the DOM document
  3. get some data from the DOM
  4. display some sort of message if the RSS can't be loaded

Enter the PHP

#!/usr/bin/env php
<?php
// create a new DOMDocument object
$dom new DOMDocument();
  //load a remote xml file
  $result $dom->load("http://blog.lettersandlight.org/rss");
  //did the load work?
  if ($result) {
    //get an array of the items in the rss
    $items $dom->getElementsByTagName('item');
    //loop through the array 
    foreach($items as $item){
      //get the title of the current item
      $title $item->getElementsByTagName('title')->item(0)->nodeValue;
      //get the description of the current item
      $desc $item->getElementsByTagName('description')->item(0)->nodeValue;
      //output some of the collected data
      echo "$title\n";
      echo "$desc\n";
    }
  else {
    echo "there was a problem reading the rss feed, bummer\n";
  }
?>

The code is also available in the hoof at http://hoof.jezra.net/snip/nR

Hopefully the code is self explanatory (that is what code comments are for), because i don't like going through code in a line by line fashion. I also don't like the ISO standard used for the 'PubDate' in an RSS feed, but I'll save that rant for some other time.

Now quit reading and go do something simple.

Comments
Name:
not required
Email:
not required (will not be displayed)
Website:
not required (will link your name to your site)
Comment:
required
Please do not post HTML code or bbcode unless you want it to show up as code in your post. (or if you are a blog spammer, in which case, you probably aren't reading this anyway).
Prove you are human by solving a math problem! I'm sorry, but due to an increase of blog spam, I've had to implement a CAPTCHA.
Problem:
9 minus 6
Answer:
required
  • Tags:
  • PHP
subscribe
 
2019
2016
2015
2014
2013
2012
2011
2010
December
November
October
September
August
July
June
May
April
March
February
January
2009
December
November
October
September
August
July
June
May
April
March
February
January
2008