note 86428 modified in function.simplexml-load-string by danbrown

From: Date: Sat, 18 Oct 2008 15:45:47 +0000
Subject: note 86428 modified in function.simplexml-load-string by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-145472@lists.php.net to get a copy of this message
I wanted to convert an array containing strings and other arrays of the same type into a simplexml object. Here is the code of the function array2xml that I've developed to perform this conversion. Please note that this code is simple without any checks. <?php function array2xml($array, $tag) { function ia2xml($array) { $xml=""; foreach ($array as $key=>$value) { if (is_array($value)) { $xml.="<$key>".ia2xml($value)."</$key>"; } else { $xml.="<$key>".$value."</$key>"; } } return $xml; } return simplexml_load_string("<$tag>".ia2xml($array)."</$tag>"); } $test['type']='lunch'; $test['time']='12:30'; $test['menu']=array('entree'=>'salad', 'maincourse'=>'steak'); echo array2xml($test,"meal")->asXML(); ?> --was-- I wanted to convert an array containing strings and other arrays of the same type into a simplexml object. Here is the code of the function array2xml that I've developed to perform this conversion. Please note that this code is simple without any checks. function array2xml($array, $tag) { function ia2xml($array) { $xml=""; foreach ($array as $key=>$value) { if (is_array($value)) { $xml.="<$key>".ia2xml($value)."</$key>"; } else { $xml.="<$key>".$value."</$key>"; } } return $xml; } return simplexml_load_string("<$tag>".ia2xml($array)."</$tag>"); } $test['type']='lunch'; $test['time']='12:30'; $test['menu']=array('entree'=>'salad', 'maincourse'=>'steak'); echo array2xml($test,"meal")->asXML(); http://php.net/manual/en/function.simplexml-load-string.php

« previous php.notes (#145472) next »