Tech Notes

Generate XML from a Two-Dimensional Array — PHP

PHP code that generates an XML file from a two-dimensional array with a known structure.

I searched a lot for PHP code to generate XML from a two-dimensional array, but none of the examples I found worked properly. The following code generates an XML file from a two-dimensional array. Note that it only works for arrays with the structure shown below.

array(1) {
  ["share_friend_list"]=>;
  array(3) {
    ["your_name"]=>
    string(12) "Sarath"
    ["friends"]=>
    array(1) {
      ["friend"]=>
      array(3) {
        [0]=>
        array(2) {
          ["name"]=>
          string(6) "Ryan"
          ["msisdn"]=>
          string(9) "213412414"
        }
        [1]=>
        array(2) {
          ["name"]=>
          string(12) "Nash"
          ["msisdn"]=>
          string(9) "123423421"
        }
        [2]=>
        array(2) {
          ["name"]=>
          string(9) "Ashish"
          ["msisdn"]=>
          string(9) "123421342"
        }
      }
    }
    ["your_email"]=>
    string(19) "sarath.dr@gmail.com"
$filePath = $this->xmlFilePath.$this->today.' - '.$type.'.xml';
        $this->doc->formatOutput = true;
if( ! file_exists( $filePath ) )
        {
               $r = $this->doc->createElement( "data" );
               $this->doc->appendChild( $r );
        }
        else
        {
            @$this->doc->load( $filePath );
            $r  = $this->doc->getElementsByTagName('data')->item(0);
        }
$this->extract( $info , $r  );
try
        {
$this->doc->saveXML();
            $this->doc->save( $filePath );
        }
        catch ( Exception $e )
        {
}
public function extract( $info , $b )
    {
if( is_array( $info ) && is_array( $info[ key($info)]) )
        {
                $temp = $b;
// New parent node
                if( is_integer(  key($info) )  )
                {
                     $this->extract( $info[ key($info)], $b );
                     if( count( array_slice(  $info , 1 ) ) > 0  )
                     $b = $this->parentNode->appendChild( $this->doc->createElement( $this->parentName ));
                }
               else
                {   // Inner nodes
                    $b = $b->appendChild(  $this->doc->createElement( key($info) ) ) ;
$this->parentNode = $temp;
                    $this->parentName = key($info);
                    $this->extract( $info[ key($info)], $b );
                    $b = $temp;
}
}
        else
        {
            $temp = $this->doc->createElement( key($info) );
            $temp->appendChild( $this->doc->createTextNode( $info[ key($info)] ) );
$b->appendChild( $temp );
}
$newArray = array_slice(  $info , 1 ) ;
if( is_array( $newArray ) && count( $newArray ) > 0  )
        {
               $this->extract( $newArray, $b );
        }
        else
        {
            return;
        }
}
Out put XML.
Sarath
Ryan
        213412414
Nash
        123423421
Ashish
        123421342
sarath.dr@gmail.com