下面是网上的
class arraytoxml 
{ 
/** 
* the main function for converting to an xml document. 
* pass in a multi dimensional array and this recrusively loops through and builds up an xml document. 
* 
* @param array $data 
* @param string $rootnodename - what you want the root node to be - defaultsto data. 
* @param simplexmlelement $xml - should only be used recursively 
* @return string xml 
*/ 
public static function toxml($data, $rootnodename = 'data', $xml=null) 
{ 
// turn off compatibility mode as simple xml throws a wobbly if you don't. 
if (ini_get('zend.ze1_compatibility_mode') == 1) 
{ 
ini_set ('zend.ze1_compatibility_mode', 0); 
} 
if ($xml == null) 
{ 
$xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$rootnodename />"); 
} 
// loop through the data passed in. 
foreach($data as $key => $value) 
{ 
// no numeric keys in our xml please! 
if (is_numeric($key)) 
{ 
// make string key... 
$key = "unknownnode_". (string) $key; 
} 
// replace anything not alpha numeric 
$key = preg_replace('/[^a-z]/i', '', $key); 
// if there is another array found recrusively call this function 
if (is_array($value)) 
{ 
$node = $xml->addchild($key); 
// recrusive call. 
arraytoxml::toxml($value, $rootnodename, $node); 
} 
else 
{ 
// add single node. 
$value = htmlentities($value); 
$xml->addchild($key,$value); 
} 
} 
// pass back as string. or simple xml object if you want! 
return $xml->asxml(); 
} 
}
下面是我编辑过的代码
function arrtoxml($arr,$dom=0,$item=0){ 
if (!$dom){ 
$dom = new domdocument("1.0"); 
} 
if(!$item){ 
$item = $dom->createelement("root"); 
$dom->appendchild($item); 
} 
foreach ($arr as $key=>$val){ 
$itemx = $dom->createelement(is_string($key)?$key:"item"); 
$item->appendchild($itemx); 
if (!is_array($val)){ 
$text = $dom->createtextnode($val); 
$itemx->appendchild($text); 
}else { 
arrtoxml($val,$dom,$itemx); 
} 
} 
return $dom->savexml(); 
}
数组转换成xml格式
<? 
$elementlevel = 0 ; 
function array_xml($array, $keys = '') 
{ 
global $elementlevel; 
if(!is_array($array)) 
{ 
if($keys == ''){ 
return $array; 
}else{ 
return "\n<$keys>" . $array . "</$keys>"; 
} 
}else{ 
foreach ($array as $key => $value) 
{ 
$havetag = true; 
if (is_numeric($key)) 
{ 
$key = $keys; 
$havetag = false; 
} 
/** 
* the first element 
*/ 
if($elementlevel == 0 ) 
{ 
$startelement = "<$key>"; 
$endelement = "</$key>"; 
} 
$text .= $startelement."\n"; 
/** 
* other elements 
*/ 
if(!$havetag) 
{ 
$elementlevel++; 
$text .= "<$key>" . array_xml($value, $key). "</$key>\n"; 
}else{ 
$elementlevel++; 
$text .= array_xml($value, $key); 
} 
$text .= $endelement."\n"; 
} 
} 
return $text; 
} 
?>
函数描述及例子
<? 
$array = array( 
"employees" => array( 
"employee" => array( 
array( 
"name" => "name one", 
"position" => "position one" 
), 
array( 
"name" => "name two", 
"position" => "position two" 
), 
array( 
"name" => "name three", 
"position" => "position three" 
) 
) 
) 
); 
echo array_xml($array); 
?>
更多php中将数组转成xml格式的实现代码。
   
 
   