1 //XML-to- array, including the root key, ignoring empty elements and attributes, with significant errors2 functionXml_to_array ($xml )3 {4 $reg= "/< (\\w+) [^>]*?> ([\\x00-\\xff]*?) <\\/\\1>/";5 if(Preg_match_all($reg,$xml,$matches))6 {7 $count=Count($matches[0]);8 $arr=Array();9 for($i= 0;$i<$count;$i++)Ten { One $key=$matches[1] [$i]; A $val= Xml_to_array ($matches[2] [$i] );//Recursive - if(array_key_exists($key,$arr)) - { the if(Is_array($arr[$key])) - { - if(!array_key_exists(0,$arr[$key])) - { + $arr[$key] =Array($arr[$key]); - } +}Else{ A $arr[$key] =Array($arr[$key]); at } - $arr[$key][] =$val; -}Else{ - $arr[$key] =$val; - } - } in return $arr; -}Else{ to return $xml; + } - } the //Xml to array, not including root key * functionXmltoarray ($xml ) $ {Panax Notoginseng $arr= Xml_to_array ($xml); - $key=Array_keys($arr); the return $arr[$key[0]]; +}
1 //an XPATH-like array selector2 functionXml_array_select ($arr,$arrpath )3 {4 $arrpath=Trim($arrpath, ‘/‘ );5 if(!$arrpath)return $arr;6 $self= ' Xml_array_select ';7 8 $pos=Strpos($arrpath, ‘/‘ );9 $pos=$pos?$pos:strlen($arrpath);Ten $curpath=substr($arrpath, 0,$pos); One $next=substr($arrpath,$pos); A - if(Preg_match("/\\[(\\d+) \\]$/",$curpath,$predicate)) - { the $curpath=substr($curpath, 0,Strpos($curpath,"[{$predicate[1]}] ")); - $result=$arr[$curpath][$predicate[1]]; -}Else $result=$arr[$curpath]; - + if(Is_array($arr) &&!array_key_exists($curpath,$arr) ) - { + die(' key is NOT exists: '.$curpath ); A } at - return $self($result,$next); - } - //if the input array is a full numeric key, the element values are transferred sequentially to the $callback, otherwise they are transferred to $callback - functionXml_array_each ($arr,$callback ) - { in if(Func_num_args() <2) die(' Parameters error '); - if(!Is_array($arr)) die(' parameter 1 shuld is an array! '); to if(!is_callable($callback)) die(' Parameter 2 shuld is an function! '); + $keys=Array_keys($arr); - $isok=true; the foreach($keys as $key) {if(!Is_int($key)) {$isok=false; Break;}} * if($isok) $ foreach($arr as $val)$result[] =$callback($val);Panax Notoginseng Else - $result[] =$callback($arr ); the return $result; +}
/** *function simplest_xml_to_array ($xmlstring) { Return Json_decode (Json_encode ((arraysimplexml_load_string($xmlstring True);}