dsgw8802 2013-04-29 14:37
浏览 152
已采纳

php和xpath - 循环遍历特定元素的子元素

I would like to loop through each book_list in the following xml file and for each book_list loop through each book for that book_list.

<inventory>
    <book_list>
        <book>
            <author>Rowling</author>
            <title>Harry Potter</title>
        </book>
        <book>
            <author>Blyton</author>
            <title>Famous 5</title>
        </book>
    </book_list>
    <book_list>
        <book>
            <author>Bloggs</author>
            <title>Learning XML</title>
        </book>
        <book>
            <author>Jones</author>
            <title>Beginning PHP</title>
        </book>
    </book_list>
</inventory>

How can I, for each book_list, loop through each book, using xpath in a php simplexml script? Here is my code,

$booklistpath = $xml->xpath('//booklist');

foreach ($booklistpath as $booklist) {
    $bookpath = $xml->xpath('//book');
    foreach ($bookpath as $book) {
        ...
    }
}

The first loop is fine, it goes through each book_list - but the nested loop, which is meant to go through each book for that particular book_list goes through each book in the entire document. I have also tried :-

'.//book'  and 
'descendant::book'
  • 写回答

1条回答 默认 最新

  • dongsou8980 2013-04-29 15:07
    关注

    That's the right result since you're using the second xpath call on the original $xml which is the SimpleXMLElement for your whole XML document.

    To get the books for each booklist just iterate them as follow:

    $booklists = $sxe->xpath('//book_list');
    
    foreach ($booklists as $booklist) {
        foreach ($booklist->book as $book) {
            echo $book->asXML();
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办