note 21839 modified in ref.array by maxim

From: Date: Tue, 12 Nov 2002 16:07:06 +0000
Subject: note 21839 modified in ref.array by maxim
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-39385@lists.php.net to get a copy of this message
here's a little function i wrote to convert any multidimensional array to an xml tree. it has this prototype: string arr2xml (array array, [string tree_name], [[int level]) use the second argument if you want to specify a name for the top of the tree - otherwise it defaults to level0. the first call to the function is kind of a dummy top level that wraps the array inside another array and calls the function for real. dont use the third argument. thats used to keep track of the levels in all the recursive calls. heres the code: function arr2xml ($arr) { if (func_num_args () < 3) { $wrapper = (func_num_args < 2) ? array ($arr) : array (func_get_arg(1)=>$arr); $xml = arr2xml ($wrapper, '', 0); } else { $level = func_get_arg (2); while (list ($key, $val) = each ($arr)) { if ($key === (int)$key) $key = 'level'.$level; $xml .= '<'.$key.'>'; if (gettype ($val) == 'array') { $xml .= arr2xml ($val, '', $level+1); } else { $xml .= $val; } $xml .= '</'.$key.'>'; } } return $xml; } --was-- could an admin please remove my last post? this is a much better rewrite of the arr2xml () function. its more sensibly written and flexible now. theres only one required argument, the array itself. it has this prototype: string arr2xml (array array, [string tree_name], [[int level]) use the second argument if you want to specify a name for the top of the tree - otherwise it defaults to level0. the first call to the function is kind of a dummy top level that wraps the array inside another array and calls the function for real. dont use the third argument. thats used to keep track of the levels in all the recursive calls. heres the code: function arr2xml ($arr) { if (func_num_args () < 3) { $wrapper = (func_num_args < 2) ? array ($arr) : array (func_get_arg(1)=>$arr); $xml = arr2xml ($wrapper, '', 0); } else { $level = func_get_arg (2); while (list ($key, $val) = each ($arr)) { if ($key === (int)$key) $key = 'level'.$level; $xml .= '<'.$key.'>'; if (gettype ($val) == 'array') { $xml .= arr2xml ($val, '', $level+1); } else { $xml .= $val; } $xml .= '</'.$key.'>'; } } return $xml; } http://www.php.net/manual/en/ref.array.php

« previous php.notes (#39385) next »