Home  >  Article  >  php教程  >  PHP遍历解析XML成数组实现方法

PHP遍历解析XML成数组实现方法

WBOY
WBOYOriginal
2016-05-25 16:41:50846browse

<?php
public function parsexml($menus) {
    $result = array();
    foreach ($menus as $menu) {
        $tmparr = array();
        //    处理空文本节点方式a
        if ($menu->nodename != &#39;#text&#39;) {
            //    检索子元素时跳跃过文本节点  - 处理空文本节点方式b
            for ($i = 1; $i < $menu->childnodes->length; $i+= 2) {
                $anode = $menu->childnodes->item($i);
                //    子元素遍历
                $anode->childnodes->length > 1 ? $tmparr[$anode->nodename] = $this->parsexml($anode->childnodes) : $tmparr[$anode->nodename] = $anode->nodevalue;
            }
            array_push($result, $tmparr);
        }
    }
    return $result;
}
$doc = new domdocument();
$doc->load(&#39;a.xml&#39;);
//    第一种,有空文本节点
$menus = $doc->getelementsbytagname(&#39;sitemap&#39;)->item(0)->childnodes;
//    第二种,明确指定标签,序列无空文本节点。但子元素仍然有空节点
$xpath = new domxpath($doc);
$query = "/sitemap/child::a";
$menus = $xpath->query($query);


教程链接:

随意转载~但请保留教程地址★

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:php读取xml列表程序 Next article:PHP和AJAX的RSS阅读器