PHP:XML与数组互相转换

目录
  1. 把XML转化为数组
  2. 把数据转换为XML格式的数据

把XML转化为数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function 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格式的数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
function 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));