整理了一下从网上搜到的一个类。网上大多数都是类,用起来忒麻烦,弄了个精简的。欢迎使用。//XML解析函数 @zairwolf
function xml2arr($xml){
$values = array();
$index = array();
$array = array();
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($parser, $xml, $values, $index);
xml_parser_free($parser);
$i = 0;
$name = $values[$i]['tag'];
$array[$name] = isset($values[$i]['attributes']) ? $values[$i]['attributes'] : '';
$array[$name] = _xml2arr($values, $i);
return $array;
}function _xml2arr($values, &$i){
$child = array();
if(isset($values[$i]['value'])) array_push($child, $values[$i]['value']);
while ($i++ < count($values)){
switch ($values[$i]['type']){
case 'cdata':
array_push($child, $values[$i]['value']);
break;
case 'complete':
$name = $values[$i]['tag'];
if(!empty($name)){
$child[$name]= !empty($values[$i]['value'])?($values[$i]['value']):'';
if(isset($values[$i]['attributes'])) $child[$name] = $values[$i]['attributes'];
}
break;
case 'open':
$name = $values[$i]['tag'];
$size = isset($child[$name]) ? sizeof($child[$name]) : 0;
$child[$name][$size] = _xml2arr($values, $i);
break;
case 'close':
return $child;
break;
}
}
return $child;
}
function xml2arr($xml){
$values = array();
$index = array();
$array = array();
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($parser, $xml, $values, $index);
xml_parser_free($parser);
$i = 0;
$name = $values[$i]['tag'];
$array[$name] = isset($values[$i]['attributes']) ? $values[$i]['attributes'] : '';
$array[$name] = _xml2arr($values, $i);
return $array;
}function _xml2arr($values, &$i){
$child = array();
if(isset($values[$i]['value'])) array_push($child, $values[$i]['value']);
while ($i++ < count($values)){
switch ($values[$i]['type']){
case 'cdata':
array_push($child, $values[$i]['value']);
break;
case 'complete':
$name = $values[$i]['tag'];
if(!empty($name)){
$child[$name]= !empty($values[$i]['value'])?($values[$i]['value']):'';
if(isset($values[$i]['attributes'])) $child[$name] = $values[$i]['attributes'];
}
break;
case 'open':
$name = $values[$i]['tag'];
$size = isset($child[$name]) ? sizeof($child[$name]) : 0;
$child[$name][$size] = _xml2arr($values, $i);
break;
case 'close':
return $child;
break;
}
}
return $child;
}
$xml=<<<EOF
<test>
<head>this is head</head>
<body>
<items>
<item id="1">item #1</item>
<item id="2">item #2</item>
<item id="3">item #3
<desc><![CDATA[<<<test>>>>]]></desc>
</item>
</items>
</body>
</test>
EOF;print_R(xml2arr($xml));Array
(
[test] => Array
(
[head] => this is head
[body] => Array
(
[0] => Array
(
[items] => Array
(
[0] => Array
(
[item] => Array
(
[id] => 2
[1] => Array
(
[0] => item #3
[desc] => <<<test>>>>
) ) ) ) ) ) ))