Tutorials

Parsing XML file using CodeIgniter’s SimpleXML library

Mar 13, 2009 insic 56 Comments

post header
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 http://www.phpclasses.org 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.

About the author: insic

Subscribe in my RSS Feed for more updates on Web Design and Development related articles. Follow me on twitter or drop a message to my inbox.

  • Sam

    that was really swift and easy xml parsing. nice stuff.

    by the way are you planning to add this in you e-commerce application? Just asking coz your sample data is products. :) cheers

  • http://twitter.com/saurabhshah Saurabh Shah

    Nice post insic…. very helpful…. thanx for sharing….

  • http://blog.insicdesigns.com insic2.0

    @sam I dont think so, maybe not. It just happens I choose product list as sample :).

    @Saurabh Shah thanks, and thanks for the tweet also.

  • http://www.pushingbuttons.net Timothy

    A lot cleaner then I thought it would be. This can be really useful. Thanks!

  • http://www.benoitvilliere.com Ben

    I think you missed some MVC concepts here. Indeed, what if you wanna use the _getXML() function over various controllers inside your application? _getXML() should be declared outside the controller. Also, it should return $xmlData directly. Avoid HTML returns from your functions if you want pure MVC. Leave the for each inside your view, it’s going to be way clearer. ;)

    This is a really nice article, I like the way you used jQuery here :)

  • http://blog.insicdesigns.com insic2.0

    @Ben, Exactly. We can get rid actually with that _getXML() function and do the foreach() in the view.

    You can do it this way, Put this in your index() funtion in the controller.

    $this->load->library(‘simplexml’);  
    $data['xmlData'] = $this->simplexml->xml_parse($xmlRaw);

    Then do the iteration in your view. :)

  • Jorge Mudry

    Excellent post!! thanks for sharing =)

  • http://www.seansteezy.com sean steezy

    I have seen your smiling avatar on the TUTs sites for sometime, decided to come check out your website. I am very impressed! You are right up there with your knowledge to back up your comments. I am RSSing this site and look forward to learning a thing or two. I just got into Codeigniter, seems like you know a thing or two! Maybe you should do a tutorial for us NETTUTS fans?

    Thanks, keep up the great work, great site!

  • shane assandry

    I keep getting this…
    Severity: Notice
    Message: Undefined offset: 0
    Filename: libraries/Simplexml.php
    Line Number: 229

    • Michael

      the same problem happen to me .
      do u have any ideas to solve it ,3q.

  • http://blog.insicdesigns.com insic2.0

    @shane you can do this
    error_reporting(E_ALL^E_NOTICE); :P  for the mean time, I havent figure out it yet.

  • http://blog.insicdesigns.com insic2.0

    @shane here is the solution,

    on line 242 locate

    if(count($array) == 1 && $array[0]) {

    change it to

    if(count($array) == 1 && isset($array[0])) {
  • shane assandry

    Thanks that helped although initially I had problems with

    foreach($xmlData['item'] as $row)

    returning just the first node of each item.

    Then I added a second xml item and all worked fine.

  • http://www.leemunroe.com Lee Munroe

    Great stuff, thanks for sharing. Working on my first CodeIgniter project and this will come in handy.

  • http://Boplo.ir AHHP

    Great post :)

  • http://lacomunidad.elpais.com/madrid09/posts ana de madrid

    Too difficult for me.

  • Ellen

    i’m not understanding where will palce this class “class Simplexml” in codeIgniter frame work

    $this->load->library(‘parser’); is a default parser liberary ??

  • http://blog.insicdesigns.com insic2.0

    @Ellen Yes parser library is in the default package in CodeIgniter.

    And you need to save the Simplexml.php in your libraries folder.

  • http://www.mp3-deal-s.com ipod

    Very interesting posts and well written. Thx for sharing it, keep up the good work..

  • Ellen

    Hi insic2.0, thanx for your guideline can i ask you more about codeigniter ?

  • http://www.2bnat.com/vb 2bnat

    Excellent post!! thanks for sharing =)

  • Ellen

    Did u post any thing about captcha Security image for CodeIgniter?

  • http://www.kaduazevedo.com.br Kadu Azevedo

    Veeery nice.

  • http://sonao.es sonao

    Thanks very much but there are some problem when the xml file is compose by only one field

  • Sean Hutchison

    Works great, wonderful post.

    How do you pull attributes out of the node?

  • Sean Hutchison

    ahh figured it out, but for anyones reference:

    attributes can be pulled out by doing $row['@attributes']['YOURATTRIBUTE'];

    be sure to include the @, thats what was messing me up.

  • Bob

    How do I get the attributes of ARTICLE?
     
     
    <NEWSFEED>
    <ARTICLE ID=”627835″ POSTING_DATE=”16-Jun-2009″ POSTING_TIME=”09:00″ ARCHIVE_DATE=”05-Jun-2010″>
    <NEWS_TYPE>News</NEWS_TYPE>

  • http://blog.insicdesigns.com insic2.0

    @Bob try to use print_r($youVar) :) so you can see the structure of your array.

  • SX

    This is a pretty basic. Parsing such a simple XML can be done easily with raw PHP 5 using curl,simple XML object, and foreach. I would like to how easy it would be to parse a complex multidimensional XML file using codeignitor otherwise this is useless as the same can be done within 5 minutes with raw PHP.

  • Pingback: Carlos Alcala Developer Blog » Blog Archive » Codeigniter SimpleXML data parser with Table View

  • http://www.carlos-alcala.com Carlos Alcala

    Hey I have to work with XML parser to MySQL tables (not HTML) but is almost the same thing, so I made some changes to the test controller and table view to suit MVC, please view the solution in my blog (thanks insic2.0 for this Simplexml library):

    MVC Solution on Carlos Alcala Blog

    and thanks for your comments and ads clicks…

  • Paulino Pardo

    Great!!!!
    My aplication have to go trough a firewall and get raw xml data, just what is needed in this library so i could take this part out from you _getXML function

    # $filename = $fname.’.xml’;
    # $xmlfile=”./xml/”.$filename;
    # $xmlRaw = file_get_contents($xmlfile);

    Hoooah!!

    Thousand Thanks!

    The more we listen, the more we learn. The more we learn, the more we can help.

    • http://theevilteddys.nl Jeroen van Heel

      How did you get your remote XML to work mine gives an error.

      A PHP Error was encountered
      Severity: Notice
      Message: Uninitialized string offset: 0
      Filename: controllers/welcome.php
      Line Number: 30

      A PHP Error was encountered
      Severity: Warning
      Message: Invalid argument supplied for foreach()
      Filename: controllers/welcome.php
      Line Number: 30

      A PHP Error was encountered
      Severity: Notice
      Message: Undefined variable: result
      Filename: controllers/welcome.php
      Line Number: 39

      • http://Howtoresolveit,,ihavethesameerrorswithyou Beben

        How to resolve it,, i have the same errors with you

  • http://dealbit.com propellerhead

    why not simply use the php’s built in simpleXML class?

  • http://www.webmasterdubai.com webmasterdubai

    nice work and really working fine please can you update this library because i have seen in comments
    if(count($array) == 1 && isset($array[0]))

    please upate it.

  • http://www.josephmarinaccio.com Joseph Marinaccio

    Thank you for posting, awesome article!

  • Jbeetle

    I have proble with parsing some czech chars like “ř,ž,š”. When parser find this char, close xmlement :(.

    Pls help.

  • bfloch

    I second the isset(array[0]) on line 290 to prevent Errors.

    Thanks!

  • S.M. Sarwar Hasan

    I got a Error when i call
    $this->simplexml->xml_parse($xmlRaw); in codeIgniter

    The Error is in line 229
    ——————————-
    A PHP Error was encountered
    Severity: Notice
    Message: Undefined offset: 0
    Filename: libraries/simplexml.php
    Line Number: 229
    ——————that means the line is———–
    if (count ( $array ) == 1 && $array [0]) {
    ———————————
    how can i solve it….

  • http://www.jneto.net.br Neto

    Very well.
    A nice solution.
    Thanks

  • willie

    the result show up, but,
    I am always getting an error message,
    “Undefined variable: result”.
    why is that?
    can someone shine the light for me?
    thanks

  • http://www.steevenz.com steevenz

    if(count($array) == 1 && element(0,$array)){ …

    will solve the problem.. off offset = 0

  • http://www.steevenz.com steevenz

    class Simplexml {

    var $result = array();
    ……

    will solve this ““Undefined variable: result”.” error mesages

    • Jackson

      I have the above line in my Simplexml.php library file, yet I still get the following error:

      Severity: Notice

      Message: Undefined variable: result

  • Jeremy

    Hi,

    Thanks for providing this tutorial, it’s very helpful, I’m curious about a couple of things.

    How would I iterate through a series of child nodes with attributes?

    My Data looks like this:

    Baltimore 8029
    Baltimore 8031
    Dover

    New Jerson
    Melbourne
    Dover

    I tried doing a nested foreach statement, but I ran into issues getting the location name using array syntax, $location[] etc, but wasn’t sure how to target the text within that actual node. ie $location[text] also when using a nested foreach, the return $result2 stopped the parent loop from continuing.

    Would appreciate any tips you have on this.

  • Jeremy Friend

    Jeremy’s Question is very important, anyone can help him?

  • a77icu5

    You rocks !

  • http://www.blueminde.co blueminded

    Excellent class. It works perfect for me. Thanks.

  • http://www.logicsolution.rs Ivan

    I have an error in line 126
    eval($this->evalCode);

    after this line on my server, code execution stops.

    on my first server i got this error
    Fatal error: Allowed memory size of 50331648 bytes exhausted (tried to allocate 31457280 bytes) in /home/bustekcu/public_html/admin/application/libraries/Simplexml.php(126) : eval()’d code on line 6239

    on localhost everything works fine.

    Lookig forward hearing from you.

    Best regards!

  • Bidur

    It was really strange for me to parse xml file, This really help me out. loads of thanks.

  • http://the29.com Raghu

    HI
    How we can load the files from the other domain … causing this error failed to load external entity

  • http://www.webincms.com WebinCMS

    Thank for your sharing, this is very helpfull for me, but how I can get the attributes?

    Thanks

  • Nanta

    hello i’m sorry i get error notification :
    A PHP Error was encountered
    Severity: Notice

    Message: Undefined variable: result

    Filename: controllers/cobaxml.php

    how can i solved it? thx b4