Using PHP and SimpleXML to parse WordPress feeds

SimpleXML is probably the easiest way to parse a XML document. We have created a class that only has to be instantiated to get the feed’s data and added a utility function to display it in a tabular format (HTML table). We have also added some simple CSS styling to the table to make it look better than the browser’s default rendering. It has to be noted that this is just for demonstration and teaching’s sake and it could be better to use XMLReader instead of SimpleXML for lengthy XML files because SimpleXML processes the inputs at once by writing them to the memory which is not a good idea if you have a big XML file.

 

This is a practical tutorial of using SimpleXML to read XML files.

We start with the standard html skeleton, include our WordPressFeed class and start feeding it with feeds.

You can see that we have included the styles for the table in the head but you can include them in an external stylesheet and change them easily.
Then we define our class (comments are directly inserted in the code for the class):

Feed’s data can be retrieved the following way:

Then the raw results (an array of all posts/articles and their data) can be accessed with the public property:

The utility function to display the data in a table can be used the following way:\

It is important to cast the XML elements as string otherwise they would be SimpleXML objects. Also, in XML elements entitled something like dc:creator mean that the creator element is in the dc namespace and that namespace has to be accessed and the creator element retrieved.

You cannot simply access it with something like:

When we give it a WordPress feed and call the showTabular() method on the class we get a page that resembles something like the graphic below:

Feed for Website phpgang

 

To get the code for this article, please visit: http://www.phpgang.com/using-php-and-simplexml-to-parse-wordpress-feeds_824.html

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *


4 + nine =