December 28, 2014 9:29 am

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.

Using PHP and SimpleXML to parse WordPress feeds

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

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: facebook, twitter

Tutorial Categories:
  • Dinesh Kumar

    Good Article, Thanks

  • thanks very useful articals

  • ProgrammingNewbie .

    Nice to see how you can use simple array functions to build upon data!