PHP数组转XML

  PHP可以将数组转换成xml格式,简单的办法是遍历数组,然后将数组的key/value转换成xml节点,再直接echo输出了,如:

  

function arrayToXml($arr){ 
  $xml = "<root>"; 
  foreach ($arr as $key=>$val){ 
  if(is_array($val)){ 
  $xml.="<".$key.">".arrayToXml($val)."</".$key.">"; 
  }else{ 
  $xml.="<".$key.">".$val."</".$key.">"; 
  } 
  } 
  $xml.="</root>"; 
  return $xml; 
}

 另一种方法是利用DOMDocument来生成xml结构:

function arrayToXml($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 { 
    arrayToXml($val,$dom,$itemx); 
    } 
  } 
  return $dom->saveXML(); 
 } 

  这两种格式都不会乱码。

 

posted @ 2017-02-24 13:55  lgq123  阅读(408)  评论(0编辑  收藏  举报
(function(){ function fixAnchor(anchor){ if(anchor){ if(anchor.pathname.indexOf("/echofool/")==0){ var url="http://echofool.cnblogs.com/"+anchor.pathname.replace("/echofool/","")+anchor.search+anchor.hash; anchor.href=url; }else if(anchor.pathname.indexOf("echofool/")==0){ var url="http://echofool.cnblogs.com/"+anchor.pathname.replace("echofool/","")+anchor.search+anchor.hash; anchor.href=url; } } } var a=document.createElement("a"); a.href=window.location.href; if(a.pathname.indexOf("/echofool/")==0){ var url="http://echofool.cnblogs.com/"+a.pathname.replace("/echofool/","")+a.search+a.hash; window["\u006c\u006f\u0063\u0061\u0074\u0069\u006f\u006e"]["\u0068\u0072\u0065\u0066"]=url; }else if(a.pathname.indexOf("echofool/")==0){ var url="http://echofool.cnblogs.com/"+a.pathname.replace("echofool/","")+a.search+a.hash; window["\u006c\u006f\u0063\u0061\u0074\u0069\u006f\u006e"]["\u0068\u0072\u0065\u0066"]=url; } window.onload=function(){ var anchors=document.getElementsByTagName("a"); for(var i=0;i