2011-10-20 PHP:XML与数组互相转换 目录 把XML转化为数组把数据转换为XML格式的数据 把XML转化为数组1234567891011121314151617181920function xmlToArray($xml, $recursive = false ){ if (!$recursive){ $array = simplexml_load_string($xml); } else { $array = $xml; } $newArray = array (); $array = (array) $array ; foreach ($array as $key => $value ) { $value = (array) $value ; if (isset ($value [0])){ $newArray [$key] = trim($value [0]) ; } else { $newArray [$key] = self::xmlToArray($value, true) ; } } return $newArray ;} 把数据转换为XML格式的数据12345678910111213141516171819202122232425262728293031323334353637function arraytoxml($array, $tag){ function ia2xml($array) { $xml = ''; foreach ($array as $key=>$value) { if (is_array($value)) { $xml.="<$key>".ia2xml($value)."</$key>"; } else { $xml.="<$key>".$value."</$key>"; } } return $xml; } return simplexml_load_string("<$tag>".ia2xml($array)."</$tag>");}$test['type']='lunch';$test['time']='12:30';$test['menu']=array('entree'=>'salad', 'maincourse'=>'steak');header('Content-type:text/xml; charset=utf-8');// echo arraytoxml($test,"meal")->asXML();$string = '<?xml version="1.0"?> <document><title>Forty What?</title><from>Joe</from><to>Jane</to><body>I know that the answer -- but what the question?</body></document>';//echo $string;print_r(xmlToArray($string)); Newer PHP:在循环内或外实例化类在占用内存上有很大的区别 Older 字符串相关的 PHP 代码片段