xml转array
字串
$xml = simplexml_load_string($data);
$array = json_decode(json_encode($xml),TRUE);
文件
$xml = simplexml_load_file($data);
$array= json_decode(json_encode($xml),TRUE);
或者
$array = (array) simplexml_load_string( $xml_string ); //缺点,二维数组里面的还是object而不是array
array转xml
function array2xml($array, $encoding = 'utf8') {
$xml = '<?xml version="1.0" encoding="' . $encoding . '"?>';
$xml.=_array2xml($array);
return $xml;
}
function _array2xml($array) {
$xml = '';
foreach ($array as $key => $val) {
is_numeric($key)&&$key = "item id=$key";
$xml.="<$key>";
$xml.=is_array($val) ? _array2xml($val) : $val;
list($key, ) = explode(' ', $key);
$xml.="</$key>";
}
return $xml;
}