$contents = '<?xml version="1.0" encoding="UTF-8"?><msg><header><transcode>9999</transcode><time>20090305102259</time><version>1.0</version></header><body><error errorcode="9001" msg="系统异常"><error errorcode="9002" msg="程序异常"></error></body></msg>';
function xml_get_attr($source, $tag) {
preg_match_all("/(?:<${tag})([^>]*)>/im" , $source , $mat);
if(is_array($mat[1])) {
foreach($mat[1] as $k=>$tempV) {
$attr = array();
preg_match_all('/([a-zA_Z0-9]+?)\s*?(?:=)\s*?(?:[\'"]?)(.*?)(?:[\'"])/im' , $tempV, $attr);
for($i = 0 , $j = count($attr[1]) ; $i < $j ; ++$i) {
$v[$k][$attr[1][$i]] = $attr[2][$i];
}
}
return $v;
}
}
print_r(xml_get_attr($contents , 'error'));
输出:
Array (
[0] => Array ( [errorcode] => 9001 [msg] => 系统异常 )
[1] => Array ( [errorcode] => 9002 [msg] => 程序异常 )
)