Parsing XML file using CodeIgniter’s SimpleXML library

This Simplexml class provides an alternative implementation of the SimpleXML API that works under PHP 4, so if you have an application that is running under PHP4 environment this is really helpful for you.


The original class was created by Taha Paksu of and it was modified by Chris Brainard so that it would work with codeigniter.

Lets take a look at the code.

In this article we don’t need to understand what is in the code above. What is my aim is to show you how to use it.

Supposing you have an xml format like below, and you need it to present as a tabular data in an html page.

Lets start by creating our controller, to make it easier lets make use of the default controller in fresh CI installation which is the welcome controller. Now open you welcome controller and in you index function populate the code below.

In this function we load the parser library, for those who dont know what a parser library is, its a simple templating engine of codeIgniter. Im using this almost always for me to get rid if the php tag in my view. Next we have a varialble title, and a variable products which calls the _getXML function with a string parameter myxml, we use this as reference of the filename for our XML file to be parse. Then load our table_view.

Lets add the _getXML function to our controller. Add this code in your welcome controller.

This assume that the file location of your xml file is in the root of your CI installation an inside the xml folder. Then using the file_get_contents() function we load the xml data to $xmlRaw varialble. We loaded the simple XML library and then we populate it to the table element using foreach() function.

Now you only need to add a very little code in your view file.

Thats it!. Adding some quick css styling and a jQuery for table row stripe effect. You get something like this.


Adding a quick table stripe effect.

Download and include the jQuery library file in your view.

Then add this line before the tag in your view file.

And you must have a style like this in your css file.

Were done. Thanks for reading.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.