XML string to PHP array

Pass the xml string through the xml2array function, if you have any priority tag also can pass in the xml2array function as second argument.

Yesterday i wrote an article regarding PHP-CURL. When we get the API response in the PHP-Curl Method. That response will be XML or JSON formates.

This function will help you to convert the xmlstring to phparray.

function xml2array($contents, $get_attributes=1, $priority = 'tag') {
    if(!$contents) return array();

    if(!function_exists('xml_parser_create')) {
        //print "'xml_parser_create()' function not found!";
        return array();
    }

    //Get the XML parser of PHP - PHP must have this module for the parser to work
    $parser = xml_parser_create('');
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, trim($contents), $xml_values);
    xml_parser_free($parser);

    if(!$xml_values) return;//Hmm...

    //Initializations
    $xml_array = array();
    $parents = array();
    $opened_tags = array();
    $arr = array();

    $current = &$xml_array; //Refference

    //Go through the tags.
    $repeated_tag_index = array();//Multiple tags with same name will be turned into an array
    foreach($xml_values as $data) {
        unset($attributes,$value);//Remove existing values, or there will be trouble

        //This command will extract these variables into the foreach scope
        // tag(string), type(string), level(int), attributes(array).
        extract($data);//We could use the array by itself, but this cooler.

        $result = array();
        $attributes_data = array();

        if(isset($value)) {
            if($priority == 'tag') $result = $value;
            else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode
        }

        //Set the attributes too.
        if(isset($attributes) and $get_attributes) {
            foreach($attributes as $attr => $val) {
                if($priority == 'tag') $attributes_data[$attr] = $val;
                else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
            }
        }

        //See tag status and do the needed.
        if($type == "open") {//The starting of the tag '<tag>'
            $parent[$level-1] = &$current;
            if(!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
                $current[$tag] = $result;
                if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
                $repeated_tag_index[$tag.'_'.$level] = 1;

                $current = &$current[$tag];

            } else { //There was another element with the same tag name

                if(isset($current[$tag][0])) {//If there is a 0th element it is already an array
                    $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
                    $repeated_tag_index[$tag.'_'.$level]++;
                } else {//This section will make the value an array if multiple tags with the same name appear together
                    $current[$tag] = array($current[$tag],$result);//This will combine the existing item and the new item together to make an array
                    $repeated_tag_index[$tag.'_'.$level] = 2;

                    if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
                        $current[$tag]['0_attr'] = $current[$tag.'_attr'];
                        unset($current[$tag.'_attr']);
                    }

                }
                $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
                $current = &$current[$tag][$last_item_index];
            }

        } elseif($type == "complete") { //Tags that ends in 1 line '<tag />'
            //See if the key is already taken.
            if(!isset($current[$tag])) { //New Key
                $current[$tag] = $result;
                $repeated_tag_index[$tag.'_'.$level] = 1;
                if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;

            } else { //If taken, put all things inside a list(array)
                if(isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array...

                    // ...push the new element into that array.
                    $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;

                    if($priority == 'tag' and $get_attributes and $attributes_data) {
                        $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
                    }
                    $repeated_tag_index[$tag.'_'.$level]++;

                } else { //If it is not an array...
                    $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
                    $repeated_tag_index[$tag.'_'.$level] = 1;
                    if($priority == 'tag' and $get_attributes) {
                        if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well

                            $current[$tag]['0_attr'] = $current[$tag.'_attr'];
                            unset($current[$tag.'_attr']);
                        }

                        if($attributes_data) {
                            $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
                        }
                    }
                    $repeated_tag_index[$tag.'_'.$level]++; //0 and 1 index is already taken
                }
            }

        } elseif($type == 'close') { //End of tag '</tag>'
            $current = &$parent[$level-1];
        }
    }

    return($xml_array);
}

I am giving you a sample xml string below. You can copy this string and pass into the above function you will see an array which is converted from xml string to php array.

<?xml version="1.0" encoding="UTF-8"?>
<Theatres>
<Theatre>
  <TheatreName><![CDATA[Camera 12]]></TheatreName>
  <Street><![CDATA[201 South Second Street, San Jose, CA]]></Street>
  <Distance>About 1 mile</Distance>
  <Movies>
    <Movie>
      <MovieName><![CDATA[Megamind]]></MovieName>
      <times>
        <row><time>11:50am</time></row>
        <row><time>1:50pm</time></row>
        <row><time>4:15</time></row>
        <row><time>6:30</time></row>
        <row><time>8:45</time></row>

      </times>
    </Movie>
  </Movies>
</Theatre>
<Theatre>
  <TheatreName><![CDATA[Century San Jose 24 2]]></TheatreName>
  <Street><![CDATA[741 South Winchester Blvd, San Jose, CA]]></Street>
  <Distance>About 4 miles</Distance>

  <Movies>
    <Movie>
         <times>
        <row><time>12:45pm</time></row>
        <row><time>12:45</time></row>
        <row><time>12:45</time></row>

        <row><time>12:45</time></row>
        <row><time>12:45</time></row>
        <row><time>3:05</time></row>
        <row><time>3:05</time></row>
        <row><time>3:05</time></row>
        <row><time>3:05</time></row>

        <row><time>3:05</time></row>
        <row><time>5:25</time></row>
        <row><time>5:25</time></row>
        <row><time>5:25</time></row>
        <row><time>5:25</time></row>
        <row><time>5:25</time></row>

        <row><time>7:50</time></row>
        <row><time>7:50</time></row>
        <row><time>7:50</time></row>
        <row><time>7:50</time></row>
        <row><time>7:50</time></row>
        <row><time>10:10</time></row>

        <row><time>10:10</time></row>
        <row><time>10:10</time></row>
        <row><time>10:10</time></row>
        <row><time>10:10</time></row>
      </times>
    </Movie>
  </Movies>

</Theatre>
<Theatre>
  <TheatreName><![CDATA[Camera 7]]></TheatreName>
  <Street><![CDATA[1875 S. Bascom Avenue, Campbell, CA]]></Street>
  <Distance>About 4 miles</Distance>
  <Movies>
    <Movie>
      <MovieName><![CDATA[Megamind 3D]]></MovieName>
      <times>
        <row><time>4:30pm</time></row>
        <row><time>6:40</time></row>
        <row><time>8:55</time></row>
      </times>
    </Movie>

  </Movies>
</Theatre>
<Theatre>
   <TheatreName><![CDATA[West Wind Capitol 6 Drive-In]]></TheatreName>
  <Street><![CDATA[3630 Hillcap Ave, San Jose, CA]]></Street>
  <Distance>About 5 miles</Distance>
  <Movies>
    <Movie>

      <MovieName><![CDATA[Megamind]]></MovieName>
       <times>
        <row><time>7:30pm</time></row>
      </times>
    </Movie>
  </Movies>
</Theatre>
<Theatre>
  <TheatreName><![CDATA[Century 20 Oakridge and XD]]></TheatreName>
  <Street><![CDATA[925 Blossom Hill Road, San Jose, CA]]></Street>
  <Distance>About 6 miles</Distance>
  <Movies>
    <Movie>
      <MovieName><![CDATA[Megamind 3D]]></MovieName>
      <times>
        <row><time>11:45am</time></row>
        <row><time>2:15pm</time></row>
        <row><time>4:40</time></row>
        <row><time>7:05</time></row>
        <row><time>9:35</time></row>

      </times>
    </Movie>
    <Movie>
      <MovieName><![CDATA[Megamind]]></MovieName>
      <times>
        <row><time>12:25pm</time></row>
        <row><time>2:50</time></row>

        <row><time>5:25</time></row>
      </times>
    </Movie>
  </Movies>
</Theatre>
</Theatres>

If you are getting the json format then use the below function

json_decode($stringVal);

Share This Post

Related Articles

81 Responses to “XML string to PHP array”


  1. This was a definitely quite beneficial publish. In theory I’d wish to publish like this also – getting time and actual effort to make a wonderful piece of writing… but what can I say… I procrastinate alot and by no means seem to obtain anything done.


  2. This is a topic close to my heart cheers, do you have a RSS feed I can use?

  3. phen375 says:

    Effective post. I learn a new challenge on different blogs everyday. It’s stimulating to share content from other writers and be taught a little something from. I’d like to use some in this content on my blog nearby mind. Natually I’ll make a link to your websites. Appreciate your sharing sharing.


  4. After study a few of the blog posts on your website now, and I truly like your way of blogging. I added it to my bookmark internet site list and will be checking back soon. Pls check out my web site as well and let me know what you think.


  5. Considerably, this submit is de facto the sweetest on this notable topic. I harmonise together with your conclusions and will thirstily sit up for your incoming updates. Saying thanks will not just be adequate, for the outstanding clarity in your writing. I’ll directly grab your rss feed to stay informed of any updates. Admirable work and far success in your online business dealings!  Please excuse my poor English as it isn’t my first tongue.


  6. Please tell me that youre going to keep this up! Its so excellent and so important. I cant wait to read additional from you. I just feel like you know so very much and know how to make people listen to what you’ve to say. This weblog is just too cool to become missed. Wonderful things, truly. Please, PLEASE keep it up!


  7. What I wouldnt give to have a debate with you about this. You just say so many things that arrive from nowhere that Im pretty certain Id have a fair shot. Your blog is wonderful visually, I mean people wont be bored. But others who can see past the videos and the layout wont be so impressed together with your generic understanding of this topic.


  8. Please tell me that youre heading to keep this up! Its so beneficial and so important. I cant wait to read more from you. I just really feel like you know so considerably and know how to make people listen to what you’ve to say. This blog is just as well cool to become missed. Excellent things, seriously. Please, PLEASE keep it up!


  9. It’s unusual for me to find something on the internet that’s as entertaining and intriguing as what you have got here. Your page is lovely, your graphics are great, and what’s more, you use reference that are relevant to what you’re saying. You’re definitely one in a million, great job!

  10. Annuaire says:

    Hi! Your article rocks and is really a very good understand!…


  11. This website is awesome. I constantly come across something new & different right here. Thank you for that data.


  12. Incredible information provided, thank you!


  13. This blog site is really good. How can I make one like this !


  14. There is visibly a lot to know about this. I feel you made certain good points in features also.

  15. annuaire says:

    Cheers for this posting, guys, retain up the fantastic operate…

  16. mutuelle says:

    I found your weblog on google and check several of the early posts. Preserve up the excellent operate. I just additional up your RSS feed to my MSN News Reader. Seeking forward to reading through additional from you later on!…


  17. You’re not the average blog writer, man. You surely have something important to contribute to the World Wide Web. Such a good blog. I’ll come back again for more.


  18. A helpful share, I just given this onto a workfellow who was doing a little research on this. And he in fact purchased me lunch because I discovered it for him. smile.. So let me rephrase that: Thnx for the treat! But yeah Thnx for spending the time to talk about this, I feel strongly about it and enjoy learning more on this topic. If possible, as you become expertise, would you mind updating your blog with more information? It is very helpful for me. Big thumb up for this blog!

  19. mutuelle says:

    This is really a extremely beneficial read for me, Have to admit you might be 1 in the most effective bloggers I ever saw.Thanks for posting this informative article.

  20. mutuelle says:

    This website is awesome. I constantly come across something new & different right here. Thank you for that data.


  21. This website is awesome. I constantly come across something new & different right here. Thank you for that data.


  22. Quite insightful post. Never thought that it was this simple after all. I had spent a excellent deal of my time looking for someone to explain this topic clearly and you’re the only 1 that ever did that. Kudos to you! Keep it up


  23. Hi. This information proved to be very useful. Can you please provide more aspects of this subject? Thanks. finally, ensure that the conversation is appropriately wrapped up.


  24. I have linked to your site, thank you


  25. Yo, a great information dude. Thankx for sharing! However I am experiencing problem with your rss feed. Don’t know why Unable to subscribe to it. Is there anybody experiencing identical rss issue? Anyone who knows kindly reply. Thankx

  26. Partybets says:

    Oh my goodness! an astonishing information man. Thanks However I’m experiencing issue with ur rss . Fail to subscribe to it. So anyone else having similar RSS trouble? Anybody who knows please reply. Thnkx


  27. Well I really enjoyed reading it. This tip provided by you is very practical for proper planning.


  28. Your place is valueble for me. Thanks!…


  29. hey there, this might be little offtopic, but i am hosting my site on hostgator and they will suspend my hosting in 4days, so i would like to ask you which hosting do you use or recommend?


  30. I have been checking out many of your stories and it’s pretty nice stuff. I will surely bookmark your site.

  31. mutuelle says:

    Cheers for this posting, guys, retain up the fantastic operate…


  32. Ive been meaning to read this and just never received a chance. Its an issue that Im really interested in, I just started reading and Im glad I did. Youre a fantastic blogger, one of the greatest that Ive seen. This weblog certainly has some info on subject that I just wasnt aware of. Thanks for bringing this things to light.

  33. vlc says:

    This web site is really a walk-through for all of the info you wanted about this and didn’t know who to ask. Glimpse here, and you’ll definitely discover it.


  34. Great site. A lot of useful information here. I’m sending it to some friends!


  35. Frequently I do not put up on blogs, but I would like to say that this submit certainly pressured me to do so! genuinely great submit

  36. mutuelle says:

    Hi! Your article rocks and is really a very good understand!…


  37. Your place is valueble for me. Thanks!…

  38. mutuelle says:

    This web site is really a walk-through for all of the info you wanted about this and didn’t know who to ask. Glimpse here, and you’ll definitely discover it.


  39. What do you need to achieve?

  40. seotons says:

    Your place is valueble for me. Thanks!…


  41. Excellent brief and this article helped me alot. Say thank you I looking for your information….

  42. seotons says:

    This is really a extremely beneficial read for me, Have to admit you might be 1 in the most effective bloggers I ever saw.Thanks for posting this informative article.


  43. Well, I do not know if that’s going to work for me, however definitely worked for you! Excellent post!

  44. news says:

    I found your entry interesting do I’ve added a Trackback to it on my weblog :) ……


  45. My partner and i dont like to appear intruding but this post make me wanna bust in here as well say what a fantastic way to eat up a couple of momemts of my time, truly really interesting and significantly congrats for your efforts.


  46. I appreciate an excellent as well as informative posting I truly appreciate all of the diligence that went to the publishing.

  47. seotons says:

    This website is awesome. I constantly come across something new & different right here. Thank you for that data.

  48. seotons says:

    Hi! Your article rocks and is really a very good understand!…

  49. seotons says:

    WONDERFUL Post.thanks for share..more wait .. ;)


  50. Ive been meaning to read this and just never acquired a chance. Its an issue that Im pretty interested in, I just started reading and Im glad I did. Youre a terrific blogger, one of the finest that Ive seen. This blog undoubtedly has some info on topic that I just wasnt aware of. Thanks for bringing this stuff to light.


  51. Sick! Just acquired a brand-new Pearl and I can now read your weblog on my phone’s browser, it didn’t do the job on my outdated one.


  52. Please tell me that youre going to keep this up! Its so good and so important. I cant wait to read a lot more from you. I just feel like you know so considerably and know how to make people listen to what you’ve got to say. This blog is just too cool to become missed. Excellent stuff, actually. Please, PLEASE keep it up!


  53. I love your site cause it contain very informative article

  54. Yorum says:

    Many thanks for posting this, It?s just what I used to be researching for on bing. I?d a lot relatively hear opinions from an individual, slightly than a company internet page, that?s why I like blogs so significantly. Many thanks!


  55. Youre so right. Im there with you. Your weblog is certainly worth a read if anyone comes across it. Im lucky I did because now Ive obtained a whole new view of this. I didnt realise that this issue was so important and so universal. You unquestionably put it in perspective for me.


  56. Cheers for your downright post. I’ve been looking nearby for this site following being referred to them from a colleague and was thrilled when i was able to locate it following searching for extended time. Right wished to commentary to demonstrate my appreciation for your internet site because it is incredibly inspiring to do, and many writers don’t secure acknowledgment they deserve. I am confident I’ll be back and definitely will send my close friends

  57. ÿþT says:

    just how do you get ideas in your content? because i find your articles very engaging everytime i call at your blog.


  58. Finally, an issue that I am passionate about. I have looked for information of this caliber for the last several hours. Your site is greatly appreciated.

  59. site says:

    Cheers for this posting, guys, retain up the fantastic operate…


  60. Do you individuals have a facebook fan page? I looked for one on twitter but could not discover one, I would really like to turn into a fan!


  61. I can see that you are putting a lots of efforts into your blog. Keep posting the good work.Some really helpful information in there. Bookmarked. Nice to see your site. Thanks!


  62. Hello.This post was really interesting, especially because I was looking for thoughts on this subject last Friday.


  63. Sorry for the huge review, but I’m really loving the new Zune, and hope this, as well as the excellent reviews some other people have written, will help you decide if it’s the right choice for you.


  64. The large amount of high quality content on your site has indeed made me realize the massive authority your site carries. Incredible posts and articles all ’round. Keep up the good work.


  65. even though i do not fully agree with you on all of your opinions, i did benefit from reading this, adios for now


  66. Hey this is a real cool web site


  67. My sis informed me about your web site and the way nice it is. She’s right, I am actually impressed with the writing and slick design. It seems to me you’re just scratching the surface by way of what you’ll be able to accomplish, but you’re off to an important begin!


  68. We offer the Replica Ferrari Watches,Fake Ferrari Watches, Replica Ferrari Diamond Watches with the best quality and lowest prices. Free shipping


  69. I certainly not remark on blogs, but this a single is wonderful! Thanks.


  70. Thank you so much for this! I haven’t been this moved by a blog for a long period of time! You have got it, whatever that means in blogging. Well, You are definitely somebody that has something to say that people need to hear. Keep up the wonderful job. Keep on inspiring the people!


  71. I am always browsing online for articles that can aid me. Thx!


  72. Great blogpost, I just passed this onto a university student who was doing a little research on this. And he in fact bought me dinner because I discovered it for him.. :) . So let me rephrase that: Thankx for the treat! But yeah Thnx for spending the time to discuss this, I feel strongly about it and love reading more on this topic. If possible, as you become expertise, would you mind updating your blog with more info? It is highly helpful for me. Two thumb up for this post!


  73. Very nice info and right to the point. I don’t know if this is in fact the best place to ask but do you people have any thoughts on where to hire some professional writers? Thx :)


  74. Yo, a brilliant information man. Thank you However I’m having issue with ur rss . Unable to subscribe to it. So anybody having similar rss feed problem? Anybody who can assist please respond. Thankx


  75. Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me. The idea of a grassroots campaign was heartily received during the 2000 Presidential primaries when Democratic contender Howard Dean showed promise early on by relying on voters instead of party mechanics to garner support.


  76. Hello. impressive job. I did not anticipate this. This is a fantastic story. Thanks!


  77. As a Newbie, I am constantly browsing online for articles that can be of assistance to me. Thank you


  78. We enjoy your approach you very enthusiastic about what one are producing. Always keep this wonderful posts!

  79. nice one says:

    Thanks a lot…

    Hi, I really appreciate your post, it was really informative. I’ll be looking forward for your next post….

  80. jasa seo says:

    hi mate…

    I simply desired to thank you very much yet again. I do not know the things that I would have achieved without the secrets shown by you relating to that industry. It was before the hard situation in my position, however , finding out a skilled techniqu…


  81. Truly good site thank you so much for your time in publishing the posts for all of us to learn about.

Leave a Reply

*