<?php
$tree = GetXMLTree("example.xml");
echo "<pre>";
print_r($tree);
echo "</pre>";
function GetXMLTree($file)
{
$data = file_get_contents($file) or die("Can't read file: ".$file);
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);
$items = array();
$level = 0;
$parents = array();
$items[0] = '';
$parents[] = &$items[0];
foreach ($vals as $xml_elem)
{
if ($xml_elem['type'] == 'open')
{
if($level>0 && array_key_exists('children',$parents[$level-1]))
{
$SubLevel = count($parents[$level-1]['children']);
}
else
{
$SubLevel = 0;
}
$cChild = 0;
$parents[$level] = &$parents[$level-1]['children'][$SubLevel];
$parents[$level]['name'] = strtolower($xml_elem['tag']);
$parents[$level]['type'] = 'complete';
$level++;
if(array_key_exists('attributes',$xml_elem))
{
$parents[$level-1]['attributes'] = $xml_elem['attributes'];
}
}
if($xml_elem['type'] == 'complete')
{
$parents[$level-1]['children'][$cChild]['name'] = strtolower($xml_elem['tag']);
$parents[$level-1]['children'][$cChild]['type'] = 'complete';
$parents[$level-1]['children'][$cChild]['value'] = $xml_elem['value'];
if(array_key_exists('attributes',$xml_elem))
{
$parents[$level-1]['children'][$cChild]['attributes'] = $xml_elem['attributes'];
}
$cChild++;
}
if($xml_elem['type'] == 'close')
{
$level--;
}
}
return $parents[0];
} // function GetXMLTree($file)
?>
|