20090201

Simple atom aggregator in PHP (with source code)

I wrote a small class to fetch and parse atom feeds in PHP. This could be useful to someone, so I release it under the GPL. The result of this little project can be seen on my web site. Prominently featured at the top of the page is a list with my recent blog posts aggregated from various web services.

This was an interesting little project, which lends itself as a nice example for people interested in PHP programming. Note though that PHP is not really my area of expertise, so there are likely ways this could be improved. Leave a comment!

This fun little project consists of two classes: Entry and AtomParser. AtomParser fetches a feed and parses its contents. This is made easy by PHP's XML Parser facilities. The information likely to be interesting to people wanting to show the contents of a blog on a different website (most importantly title and text of the post) are stored in Entry objects.

For convenience AtomParser supports adding multiple sources and sorting them by date. Retrival of the entries is realized in a for-loop friendly getEntryIterator(), hasNextEntry(), getNextEntry() way.

Combined this allows the following snippet to work:

$parser = new AtomParser();
$parser->addSource("http://identi.ca/api/statuses/user_timeline/mauder.atom", true /*microblog*/);
$parser->addSource("http://drowstar.blogspot.com/feeds/posts/default", false);
$parser->sortByDate();

for($iterator = $parser->getEntryIterator();
$parser->hasNextEntry();
) {
$entry = $parser->getNextEntry();
printf("<h1>%s (%s)</h1>\n%s\n", $entry->title, date("Y-m-d", $entry->date), $entry->text);
}


The snippet I actually use on mauder.name is rather more complicated, but as the presentation is very much a matter of taste I leave it to the reader to find one he is happy with.

I release this snippet under the GPL. Email me if you need a different license.

No comments: