-
-
// Convert Xml to array, including root keys, ignoring empty elements and attributes, there are still major errors - function xml_to_array( $xml )
- {
- $reg = "/ <(\w+)[^>]*?>([\x00-\xFF]*?)<\/\1>/";
- if(preg_match_all($reg, $xml, $matches) )
- {
- $count = count($matches[0]);
- $arr = array();
- for($i = 0; $i < $count; $i++)
- {
- $key = $matches [1][$i];
- $val = xml_to_array( $matches[2][$i] ); // Recursion
- if(array_key_exists($key, $arr))
- {
- if(is_array($arr[ $key]))
- {
- if(!array_key_exists(0,$arr[$key]))
- {
- $arr[$key] = array($arr[$key]);
- }
- }else{
- $arr[$key] = array($arr[$key]);
- }
- $arr[$key][] = $val;
- }else{
- $arr[$key] = $val;
- }
- }
- return $arr;
- }else{
- return $xml;
- }
- }
// Xml to array, excluding root key
- function xmltoarray( $xml )
- {
- $ arr = xml_to_array($xml);
- $key = array_keys($arr);
- return $arr[$key[0]];
- }
// XPATH-like array selector
- function xml_array_select( $arr, $arrpath )
- {
- $arrpath = trim( $arrpath, '/' );
- if(!$arrpath) return $arr;
- $self = 'xml_array_select';
-
- $pos = strpos( $arrpath, '/' );
- $pos = $pos ? $pos : strlen($arrpath);
- $curpath = substr($arrpath, 0, $pos);
- $next = substr($arrpath, $pos);
-
- if(preg_match("/\[(\d+)\]$/",$curpath,$predicate))
- {
- $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 );
- }
-
- return $self($result, $next);
- }< /p>
// If the input array is an all-numeric key, then the element values will be transferred to $callback in sequence, otherwise it will transfer itself to $callback
- function xml_array_each( $arr, $callback )
- {
- if (func_num_args()<2) die('parameters error');
- if(!is_array($arr)) die('parameter 1 shuld be an array!');
- if(!is_callable($callback)) die ('parameter 2 shuld be an function!');
- $keys = array_keys($arr);
- $isok = true;
- foreach( $keys as $key ) {if(!is_int($key)) {$isok = false; break;}}
- if($isok)
- foreach( $arr as $val ) $result[] = $callback($val);
- else
- $result[] = $callback( $arr );
- return $result;
- }
- ?>
-
Copy code
|