XML2Array: Convert XML to Array in PHP

XML2Array is a class to convert XML to an array in PHP. It returns an array which can be converted back to XML using the Array2XML class.

It can take a string XML as input or an object of type DOMDocument.

Conventions

  • attributes stored as key value pairs under ['tag_name']['@attributes']
  • CDATA nodes are stored under ['tag_name']['@cdata']
  • In case a node has attributes, the value will be stored in ['tag_name']['@value']

Usage

The usage is pretty simple. You have to include the class file in your code and call the following function.

$array = XML2Array::createArray($xml);
print_r($array);

Important thing to note is that the $array returned can be converted back to XML using the Array2XML class.

Example

The Following XML:

<?xml version="1.0" encoding="UTF-8"?>
<movies type="documentary">
  <movie>
    <title>PHP: Behind the Parser</title>
    <characters>
      <character>
        <name>Ms. Coder</name>
        <actor>Onlivia Actora</actor>
      </character>
      <character>
        <name>Mr. Coder</name>
        <actor>El ActÓr</actor>
      </character>
    </characters>
    <plot><![CDATA[So, this language. It's like, a programming language. Or is it a scripting language? 
All is revealed in this thrilling horror spoof of a documentary.]]></plot>
    <great-lines>
      <line>PHP solves all my web problems</line>
    </great-lines>
    <rating type="thumbs">7</rating>
    <rating type="stars">5</rating>
  </movie>
</movies>

will generate the following output:

array (
    'movies' => array (
        'movie' => array (
            'title' => 'PHP: Behind the Parser',
            'characters' => array (
                'character' => array (
                    0 => array (
                        'name' => 'Ms. Coder',
                        'actor' => 'Onlivia Actora',
                    ),
                    1 => array (
                        'name' => 'Mr. Coder',
                        'actor' => 'El ActÓr',
                    ),
                ),
            ),
            'plot' => array (
                '@cdata' => 'So, this language. It\'s like, a programming language. Or is it a scripting language? 
All is revealed in this thrilling horror spoof of a documentary.',
            ),
            'great-lines' => array (
                'line' => 'PHP solves all my web problems',
            ),
            'rating' => array (
                0 => array (
                    '@value' => '7',
                    '@attributes' => array (
                        'type' => 'thumbs',
                    ),
                ),
                1 => array (
                    '@value' => '5',
                    '@attributes' => array (
                        'type' => 'stars',
                    ),
                ),
            ),
        ),
        '@attributes' => array (
            'type' => 'documentary',
        ),
    ),
)

Download (v0.2, 04 Mar, 2012)

The code is released under Apache License 2.0

Plain text PHP source | Formatted PHP source

• • •

10 Responses to XML2Array: Convert XML to Array in PHP

  1. Sascha says:

    Thank you very much for this class, it has helped me greatly. I just found a minor issue in this version:

    <?php
    if(get_class($input_xml) != 'DomDocument') {
     throw new Exception('[XML2Array] The input XML object should be of type: DomDocument.');
    }
    ?>

    The problem is that get_class will return the following:
    string(11) "DOMDocument"

    Comparing is case sensitive so you always run into this exception even if you use a proper DOMDocument as input.

    Cheers

  2. Vicary says:

    Your work on Array2XML is like a charm, but this class I would prefer three lines of code instead a whole new class.

    <?php
    $xml = simplexml_load_string($xml);
    $array = json_encode($xml);
    $array = json_decode($xml, true);
    ?>
  3. edward.CC says:

    consider next xml

    using this class some attributes with namespaces are changed, “xsi:schemaLocation” will be converted to “schemaLocation”

  4. Thank you for this class, XML2Array, which I intend to use in my work.

    In the sample XML, you included the character Ó, which causes the class methods not to work, not a deal breaker for me, but it would be a nice to have.

    Any plans / remarks ?

  5. Don Coryon says:

    I would like to include this code in a Drupal module I am building. However, there is a licensing conflict with Apache 2.0 and GPL v2. Would it be possible to get a special exemption and re-license this code as GPL v2 as far as it pertains to my Drupal module?

    Thank you.