donglao4370 2017-10-29 09:37
浏览 29
已采纳

如何读取XML文件的php DOM中的分隔符?

I've some XML files and I've to read and convert them in HTML.

The format of the XML is this:

<book pages="2">

    <page n="1" />

    <entry>
        ...
    </entry>
    <entry>
        ...
    </entry>
    <entry>
        ...
    </entry>

    <page n="2" />

    <entry>
        ...
    </entry>
    <entry>
        ...
    </entry>
    <entry>
        ...
    </entry>

    <endpages />

</book>

How i can extract an array of the entries only of a single page?

Thanks in advance!

展开全部

  • 写回答

2条回答 默认 最新

  • douniang3866 2017-10-29 13:34
    关注

    I suggested using XPath for this in my original comment, however, I've been playing around with some XPath expressions for this using a combination of following-sibling and preceding-sibling but I can't get it to work properly with this XML structure.

    A bit of a hacky way of doing this is by just fetching everything after a given page number, and stopping when you find the next <page /> or <endpages /> element:

    $dom = new DOMDocument("1.0", "UTF-8");
    $dom->load($xmlFile);
    
    $xp = new DOMXPath($dom);
    
    $pageNo = 2;
    
    $list = $xp->query("/book/page[@n='" . $pageNo . "']/following-sibling::*");
    
    foreach ($list as $node) {
        if ($node->nodeName == 'page' || $node->nodeName == 'endpages') {
            break;
        }
    
        echo $node->textContent . "<br />"; // <entry /> node
    }
    

    I'm quite sure this will not perform very well if you have a lot of pages in the XML file and you're trying to fetch only the elements of page one, but in terms of lines of code this is overseeable and maybe someone else has some ideas on how to optimise the XPath expression.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?