亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PHP DOM XML 到數組的轉換

PHP DOM XML 到數組的轉換

PHP
BIG陽 2023-07-21 18:15:36
我有一個 xml 文檔如下:<?xml version="1.0" encoding="UTF-8" ?><books>    <book>        <name>Title One</name>        <year>2014</year>        <authors>            <author>                <name>Author One</name>            </author>        </authors>    </book>    <book serie="yes">        <name>Title Two</name>        <year>2015</year>        <authors>            <author>                <name>Author two</name>            </author>            <author>                <name>Author three</name>            </author>        </authors>    </book>    <book serie="no">        <name>Title Three</name>        <year>2015</year>        <authors>            <author>                <name>Author four</name>            </author>        </authors>    </book></books>我想將它轉換成下面的數組。array(    array('Tittle one', 2014, 'Author One'),    array('Tittle two', 2015, 'Author two, Author three'),    array('Tittle three', 2015, 'Author four'),);我下面的代碼無法生成我想要的數組結構:function arrayRepresentation(){    $xmldoc = new DOMDocument();    $xmldoc->load("data/data.xml");    $parentArray =  array();    foreach ($xmldoc->getElementsByTagName('book') as $item) {        $parentArray[] = array_generate($item);    }    var_dump($parentArray);}function array_generate($item){    $movieArray = array();    $childMovieArray = array();    for ($i = 0; $i < $item->childNodes->length; ++$i) {        $child = $item->childNodes->item($i);        if ($child->nodeType == XML_ELEMENT_NODE) {            if(hasChild($child)){                $childMovieArray = array_generate($child);            }        }        $movieArray[] = trim($child->nodeValue);    }        if(!empty($childMovieArray)){        $movieArray = array_merge($movieArray,$childMovieArray);    }        return $movieArray;}基本上我循環遍歷節點來獲取 xml 元素值。然后我檢查我的節點是否有更多的子節點,如果有,我再次循環它以獲取值。我無法推斷出一種方法:(i)不會給我一些空數組元素(ii)檢查任何子節點并將所有 xml 同級元素放入單個字符串中
查看完整描述

1 回答

?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

PHP DOM 支持 Xpath 表達式來獲取特定節點和值。這大大減少了您需要的循環和條件的數量。


這是一個演示:


// bootstrap the XML document

$document = new DOMDocument();

$document->loadXML($xml);

$xpath = new DOMXpath($document);


$data = [];

// iterate the node element nodes

foreach ($xpath->evaluate('/books/book') as $book) {

    $authors = array_map(

       fn ($node) => $node->textContent,

       // fetch author name nodes as an array

       iterator_to_array($xpath->evaluate('authors/author/name', $book))

    );

    $data[] = [

        // cast first name element child to string

        $xpath->evaluate('string(name)', $book),

        // cast first year element child to string

        $xpath->evaluate('string(year)', $book),

        implode(', ', $authors)

    ];

}


var_dump($data);


查看完整回答
反對 回復 2023-07-21
  • 1 回答
  • 0 關注
  • 138 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號