为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 75 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信