Array2XML: convert PHP Array to XML (with attributes and CDATA)

Array2XML is a class to convert an array in PHP to XML. It allows you to parse a multidimensional array into XML including attributes unlike other scripts available on the internet. It returns the XML in form of DOMDocument object for further manipulation.

This library is very helpful when you know the scheme before hand and you have to generate an XML for it using dynamic values from the database.

The resulting XML can be converted back to an Array using the XML2Array class.

Usage

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

$xml = Array2XML::createXML('root_node_name', $php_array);
echo $xml->saveXML();

Important thing to note is that the $xml object returned is of type DOMDocument and hence you can perform further operations on it.

Optionally you can also set the version of XML and encoding by calling the Array2XML::init() function before calling the Array2XML::createXML() function.

Array2XML::init($version /* ='1.0' */, $encoding /* ='UTF-8' */);

It throws exception if the tag name or attribute name has illegal chars as per W3C spec.

Array Structure conventions

The array passed to the Array2XML::createXML() function follows few conventions, which are quite literal and easy to learn/use. The examples below demonstrate their usage

  1. Empty Nodes: Following will create an empty node.
    $books = array();  // or
    $books = null;  // or
    $books = '';
    $xml = Array2XML::createXML('books', $books);
     
    // all three cases above create <books/>
  2. Attributes: Attributes can be added to any node by having a @attributes key in the array
    $books = array(
        '@attributes' => array(
            'type' => 'fiction',
            'year' => 2011,
            'bestsellers' => true
        )
    );
    $xml = Array2XML::createXML('books', $books);
     
    // creates <books type="fiction" year="2011" bestsellers="true"/>
  3. Node Value: For nodes without attributes, value can be assigned directly, else we need to have a @value key in the array. Following examples will make it clear
    $books = 1984;  // or
    $books = array(
        '@value' = 1984
    );
    // creates <books>1984</books>
     
    $books = array(
        '@attributes' => array(
            'type' => 'fiction'
        ),
        '@value' = 1984
    );
    // creates <books type="fiction">1984</books>
     
    $books = array(
        '@attributes' => array(
            'type' => 'fiction'
        ),
        'book' => 1984
    );
    /* creates 
    <books type="fiction">
      <book>1984</book>
    </books>
    */
     
    $books = array(
        '@attributes' => array(
            'type' => 'fiction'
        ),
        'book'=> array('1984','Foundation','Stranger in a Strange Land')
    );
    /* creates 
    <books type="fiction">
      <book>1984</book>
      <book>Foundation</book>
      <book>Stranger in a Strange Land</book>
    </books>
    */
  4. Complex XML: Following example clarifies most of the usage of the library
    $books = array(
        '@attributes' => array(
            'type' => 'fiction'
        ),
        'book' => array(
            array(
                '@attributes' => array(
                    'author' => 'George Orwell'
                ),
                'title' => '1984'
            ),
            array(
                '@attributes' => array(
                    'author' => 'Isaac Asimov'
                ),
                'title' => array('@cdata'=>'Foundation'),
                'price' => '$15.61'
            ),
            array(
                '@attributes' => array(
                    'author' => 'Robert A Heinlein'
                ),
                'title' =>  array('@cdata'=>'Stranger in a Strange Land'),
                'price' => array(
                    '@attributes' => array(
                        'discount' => '10%'
                    ),
                    '@value' => '$18.00'
                )
            )
        )
    );
    /* creates 
    <books type="fiction">
      <book author="George Orwell">
        <title>1984</title>
      </book>
      <book author="Isaac Asimov">
        <title><![CDATA[Foundation]]></title>
        <price>$15.61</price>
      </book>
      <book author="Robert A Heinlein">
        <title><![CDATA[Stranger in a Strange Land]]</title>
        <price discount="10%">$18.00</price>
      </book>
    </books>
    */

Detailed Example

You can see a much more detailed example here.

Download (v0.8, 2 May, 2012)

The code is released under Apache License 2.0

Plaint text PHP source | Formatted PHP source

Tags: , , , ,
Posted in lab | 58 Comments
• • •

Dish TV Password Menance

I got a new Dish TV HD connection. Watching Live Cricket in HD is a very amazing experience. I tried to create a new online account to manage subscription etc.

Immediately after signup (choosing a new password at the time of signup), I was show (forced) a screen to change the password with the following message:

To increase your online web security, kindly change your password in every 15 days.

On a site like Dish TV, the frequency for visit should be at most once per month (to renew the subscription et al.) and the above policy means I have to change my password every time I would login to the website. That makes this the strictest password policy enforcement I have seen till date :)

Given the target audience of the website, changing password so often means people are more prone to forgetting their password and more trouble (calls/emails) for the customer care department.

What can be the logic behind such a policy. A novice at work?

Tags: , , , , ,
Posted in blog | 1 Comment
• • •

Talk: Facebook Platform Best Practices

My talk at Facebook Developer Garage at Bangalore on 10th Oct 2010. The talk was about how to make your application grow viraly on Facebook and few best practices to retain your users.
more

Tags: , , ,
Posted in blog | 1 Comment
• • •

Ternary nuances in PHP

Yesterday while working on one of my projects, I came across a weird scenario: a very simple statement written in PHP was not behaving the way it should.

Below is the simplified version of the code I was working with:

1
2
$i = 1;
echo $i == 1 ? 'One' : $i == 2 ? 'Two' : 'Three';

more

Posted in lab | 1 Comment
• • •

Vacation Relaxation?

Vaction Relaxation
exactly how I feel :)

Tags: ,
Posted in inspiration | Leave a comment
• • •

If you don’t give a damn or you don’t understand…

You can cry all you want but your cry wont get you no where;
You can run all you want but your mind wont get you no where;
You can scream all you want but your scream wont get you no where;
You can dream all you want ‘coz your dream might get you somewhere.

If you don’t give a damn or you don’t understand, its like you going nowhere. more

Tags: , ,
Posted in inspiration | 1 Comment
• • •

Getting most out of Amazon S3

Amazon S3 is a very useful service. S3, according to the official Amazon Web Services website is

Amazon S3 is storage for the Internet. It is designed to make web-scale computing easier for developers.

Its a no frills service and does exactly what it promises — makes it easy for developers so that they can concentrate on features and leave the scaling to Amazon. If you are new to Amazon S3, heres a good starting guide for you.

S3 is like a sharp sword, you must know how to play with it lest you can hurt yourself. Thats exactly what happened to me. more

Tags: , , ,
Posted in lab | 17 Comments
• • •

Powerpoint / Slideshow Karaoke

Last year while I was at SlideShare.net, me and my friends were thinking of some cool ways to use our API. At the same time we were checking out emails from our users about how they are using sideshows in more fun way. Just then we came to know about PowerPoint Karaoke here and here.

Demo

After a few hours of javascript hacking, this is what I came up with.
more

Tags: , , , ,
Posted in lab | Leave a comment
• • •

Water water everywhere!

You might have heard about the recent Floods in Orissa. Its a unfortunate event for Orissa and its people. Its one of the most worst flood to hit Orissa ever. It has already displaced 5 lakh people and relief operations are facing difficulties as many areas are totally cutoff by road.

more

Tags:
Posted in blog | Leave a comment
• • •

"Excellence" is a drive from inside

Excellence and perfection are so relative terms that its very difficult to explain or describe your thoughts about them to a second person. Even if you try your best to explain, often you fail to produce the same spark that kindles in you.

The following short story was forwarded to me by my friend Ameet.

more

Tags: , ,
Posted in inspiration | 2 Comments
• • •