note 42434 deleted from ref.xml by didou
| From: | didou@php.net | Date: | Thu, 03 Feb 2005 19:47:17 +0000 |
| Subject: | note 42434 deleted from ref.xml by didou | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-84464@lists.php.net to get a copy of this message | ||
Note Submitter: rcotta at ig dot com dot br
----
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 ;)