php xml 解析成数组(目前仅支持5级,需要照样添加代码就行)

<?
$data = "<para><note>simple note</note><cd><dd><ee>ff</ee></dd></cd><ddd></ddd></para>";
$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);

$arr = array();
$p = array();
foreach ($values as $k=>$v){
        if($v[type] == 'open'){
                $p[] = $v[tag];
        }elseif($v[type] == 'complete'){
                switch (count($p)){
                        case 1: $arr[$p[0]][$v[tag]] = $v[value];break;
                        case 2: $arr[$p[0]][$p[1]][$v[tag]] = $v[value];break;
                        case 3: $arr[$p[0]][$p[1]][$p[2]][$v[tag]] = $v[value];break;
                        case 4: $arr[$p[0]][$p[1]][$p[2]][$p[3]][$v[tag]] = $v[value];break;
                        case 5: $arr[$p[0]][$p[1]][$p[2]][$p[3]][$p[4]][$v[tag]] = $v[value];break;
                }
                #print_r($arr);echo "<br /><br />";
        }elseif($v[type] == 'close'){
                unset($p[count($p)-1]);
        }
}
print_r($arr);echo "<br /><br />";
?>

你可能感兴趣的:(xml,PHP,职场,休闲,解析成数组)