PHP XML和数组互相转换

数组转XML
[php]
function arrayToXml($arr)
{
$xml = "<xml>";
foreach ($arr as $key=>$val)
{
if (is_numeric($val)){
$xml.="<".$key.">".$val."</".$key.">";
}else{
$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
}
}
$xml.="</xml>";
return $xml;
}
[/php]

[php]
function array2xml($data, $name='root', &$doc=null, &$node=null){
if ($doc==null){
$doc = new DOMDocument('1.0','UTF-8');
$doc->formatOutput = TRUE;
$node = $doc;
}

if (is_array($data)){
foreach($data as $var=>$val){
if (is_numeric($var)){
array2xml($val, $name, $doc, $node);
}else{
if (!isset($child)){
$child = $doc->createElement($name);
$node->appendChild($child);
}

array2xml($val, $var, $doc, $child);
}
}
}else{
$child = $doc->createElement($name);
$node->appendChild($child);
$textNode = $doc->createTextNode($data);
$child->appendChild($textNode);
}

if ($doc==$node) return $doc->saveXML();
}//array2xml
[/php]

将XML转为array
[php]
//将XML转为array
function xmlToArray($xml)
{
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $values;
}
[/php]

阅读剩余
THE END