donglao4370 2017-10-29 17: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 21: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条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效