PHP 数组转XML 格式
function buildXml( $data, $wrap= 'xml' ){ $str = "<{$wrap}>"; if( is_array( $data ) ){ if( hasIndex( $data ) ){ foreach( $data as $k=>$v ){ $str .= buildXml( $v, $k ); } }else{ foreach( $data as $v ){ foreach( $v as $k1=>$v1 ) $str .= buildXml( $v1, $k1 ); } } }else $str .= $data; $str .= "</{$wrap}>"; return $str; } function hasIndex( $arr ){ return array_keys($arr) !== range(0, count($arr) - 1); } $arr1 = [ 'title'=>'title', 'bbb'=>[ 'AAA'=>12, 'BBB'=>555 ] ]; $arr2 = [ 'aaa'=>1, 'bbb'=>[ ['AAA'=>[ 'BBB'=>[ ['DDDD'=>111],['DDDD'=>222] ] ]], ['AAA'=>6] ] ]; header("Content-type: text/xml"); echo '<?xml version="1.0" encoding="utf-8"?>'; echo buildXml($arr2);
生命只有一次。