php遞迴解析數組產生xml問題 求協助

來源:互聯網
上載者:User
我的基本思路是遍曆數組 判斷當前元素有沒有名為"childs"的子數組 如果有的話 遞迴執行本函數
$config = array('root' => array('childs' => array('body' => array('childs' => array('scroller' => array('childs' => array('header' => array('childs' => array('simpleHeader' => array('childs' => array('a' => array())))),'items' => array('childs' => array('fuck' => array('childs' => array('b' => array())))))))))));header("Content-type:text/xml;Charset=UTF-8");$xml = new XMLWriter();$xml->openUri('php://output');$xml->startDocument('1.0', 'UTF-8');$xml->setIndent(true);function writeXml($array){global $xml;foreach($array as $key => $value){$xml->startElement($key);if( isset($value['childs']) && is_array($value['childs']) && count($value['childs']) > 0 ){writeXml($value['childs']);}$xml->endElement();}$xml->endDocument();$xml->flush();}writeXml($config);

為什麼產生的xml不對? items跑到了外面


回複討論(解決方案)

if 判斷的邏輯問題,你再仔細看看
php SPL裡面有遞迴器,寫起來簡單點

把
$xml->endDocument();
$xml->flush();
移出 writeXml 函數,最後執行

....writeXml($config);$xml->endDocument();$xml->flush();

把
$xml->endDocument();
$xml->flush();
移出 writeXml 函數,最後執行

....writeXml($config);$xml->endDocument();$xml->flush();


感激不盡 我一直以為邏輯有問題 糾結了半天 結果問題居然出在這

整體封裝成函數

function writeXml($array, $xml=null){  if(! $xml) {    header("Content-type:text/xml;Charset=UTF-8");    $xml = new XMLWriter();    $xml->openUri('php://output');    $xml->startDocument('1.0', 'UTF-8');    $xml->setIndent(true);    writeXml($array, $xml);    $xml->endDocument();    $xml->flush();  }else {    foreach($array as $key => $value){        $xml->startElement($key);        if( isset($value['childs']) && is_array($value['childs']) && count($value['childs']) > 0 ){            writeXml($value['childs'], $xml);        }        $xml->endElement();    }  }}
調用 writeXml($config);
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.