note 42434 added to ref.xml

From: Date: Sun, 16 May 2004 21:11:49 +0000
Subject: note 42434 added to ref.xml
Groups: php.notes 
Request: Send a blank email to php-notes+get-69675@lists.php.net to get a copy of this message
I've written this function that will parse a XML file and put its contents into an array. If more than one element with the same name on the same level coexist, the last one will overwrite the former. This is a problem for some XML but is very useful if you don't have two elements with the same name on the same level. <?php $res = makeXMLTree(file_get_contents('data.xml')); print_r($res); function makeXMLTree($data) { $ret = array(); $parser = xml_parser_create(); xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0); xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1); xml_parse_into_struct($parser,$data,$values,$tags); xml_parser_free($parser); $hash_stack = array(); foreach ($values as $key => $val) { switch ($val['type']) { case 'open': array_push($hash_stack, $val['tag']); break; case 'close': array_pop($hash_stack); break; case 'complete': array_push($hash_stack, $val['tag']); // uncomment to see what this function is doing // echo("\$ret[" . implode($hash_stack, "][") . "] = '{$val[value]}';\n"); eval("\$ret[" . implode($hash_stack, "][") . "] = '{$val[value]}';"); array_pop($hash_stack); break; } } return $ret; } ?> Create a file data.xml like this: <?xml version="1.0"?> <super> <val1>Some Value</val1> <val2>Another one</val2> <val3>This will be overwritten</val3> <val3>This one will be the one to be shown</val3> </super> And the output will be: Array ( [super1] => Array ( [val1] => Some Value [val2] => Another one [val3] => This one will be the one to be shown ) ) I hope this helps someone ;) ---- Manual Page -- http://www.php.net/manual/en/ref.xml.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+42434 Delete -- http://master.php.net/manage/user-notes.php?action=delete+42434&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+42434&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#69675) next »