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 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?