
I have searched a lot for php code to generate xml from a two dimensional array. But all of them was not working perfectly. The following code generates xml file from a two dimensional array. This only works for the array with the following structure.
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.
<?xml version="1.0"?> <data> <share_friend_list> <your_name>Sarath</your_name> <friends> <friend> <name>Ryan</name> <msisdn>213412414</msisdn> </friend> <friend> <name>Nash</name> <msisdn>123423421</msisdn> </friend> <friend> <name>Ashish</name> <msisdn>123421342</msisdn> </friend> </friends> <your_email>sarath.dr@gmail.com</your_email> </share_friend_list> </data>
