标签:style class blog code java http
1 // Xml 转 数组, 包括根键,忽略空元素和属性,尚有重大错误 2 function xml_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++) 10 { 11 $key= $matches[1][$i]; 12 $val = xml_to_array( $matches[2][$i] ); // 递归 13 if(array_key_exists($key, $arr)) 14 { 15 if(is_array($arr[$key])) 16 { 17 if(!array_key_exists(0,$arr[$key])) 18 { 19 $arr[$key] = array($arr[$key]); 20 } 21 }else{ 22 $arr[$key] = array($arr[$key]); 23 } 24 $arr[$key][] = $val; 25 }else{ 26 $arr[$key] = $val; 27 } 28 } 29 return $arr; 30 }else{ 31 return $xml; 32 } 33 } 34 // Xml 转 数组, 不包括根键 35 function xmltoarray( $xml ) 36 { 37 $arr = xml_to_array($xml); 38 $key = array_keys($arr); 39 return $arr[$key[0]]; 40 }
1 // 类似 XPATH 的数组选择器 2 function xml_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); 10 $curpath = substr($arrpath, 0, $pos); 11 $next = substr($arrpath, $pos); 12 13 if(preg_match("/\\[(\\d+)\\]$/",$curpath,$predicate)) 14 { 15 $curpath = substr($curpath, 0, strpos($curpath,"[{$predicate[1]}]")); 16 $result = $arr[$curpath][$predicate[1]]; 17 }else $result = $arr[$curpath]; 18 19 if( is_array($arr) && !array_key_exists($curpath, $arr) ) 20 { 21 die( ‘key is not exists:‘ . $curpath ); 22 } 23 24 return $self($result, $next); 25 } 26 // 如果输入的数组是全数字键,则将元素值依次传输到 $callback, 否则将自身传输给$callback 27 function xml_array_each( $arr, $callback ) 28 { 29 if(func_num_args()<2) die(‘parameters error‘); 30 if(!is_array($arr)) die(‘parameter 1 shuld be an array!‘); 31 if(!is_callable($callback)) die(‘parameter 2 shuld be an function!‘); 32 $keys = array_keys($arr); 33 $isok = true; 34 foreach( $keys as $key ) {if(!is_int($key)) {$isok = false; break;}} 35 if($isok) 36 foreach( $arr as $val ) $result[] = $callback($val); 37 else 38 $result[] = $callback( $arr ); 39 return $result; 40 }
/** * 最简单的XML转数组 * @param string $xmlstring XML字符串 * @return array XML数组 */ function simplest_xml_to_array($xmlstring) { return json_decode(json_encode((array) simplexml_load_string($xmlstring)), true); }
PHP XML To Array将XML转换为数组,布布扣,bubuko.com
标签:style class blog code java http
原文地址:http://www.cnblogs.com/syphper/p/3782292.html