Cheap Shared Hosting

Thursday, March 11, 2010

Using jQuery to parse an xml feed and create a bullet list

This one's really simple, but I end up using it a lot so why not post it?

Say you need to display an xml news feed on a site. I needed to. So I looked at how to do it with PHP, and it seemed far more over-complicated than need be for something so simple.

One again jQuery comes to the rescue. If you're not familiar with jQuery, it's a javascript library that makes javascript actually pleasant to use. I used to avoid javascript because of cross-browser issues, and everything always seemed more difficult than it needed to be. jQuery fixes all that.

The code snippet below uses jQuery to grab the XML feed, go through each item in the feed and output a simple bullet list of linked titles. Should be easy to adapt it to whatever your needs may be. Just be sure you also have the jQuery library set up on what page you use it on. It also uses a <ul id="theBox"> to put the bullet items in.


$(document).ready(function(){

var theBox = "";

$.get('XML URL HERE', {}, function(xml){
$('item',xml).each(function(){
theBox += "<li><a href=\"" +
$(this).find("link").text() + "\">" +
$(this).find("title").text() +
"</a></li>";

});
$('ul#theBox').html(theBox);
});

});

No comments: