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

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'

图片转代码服务由CSDN问答提供 功能建议

我想循环遍历以下xml文件中的每个book_list,并为每个book_list循环遍历该book_list的每本书 。

 &lt; inventory&gt; 
&lt; book_list&gt; 
&lt; book&gt; 
&lt; author&gt; Rowling&lt; / 作者&gt; 
&lt; title&gt;哈利波特&lt; / title&gt; 
&lt; / book&gt; 
&lt; book&gt; 
&lt; author&gt; Blyton&lt; / author&gt; 
&lt; title&gt; Famous 5&lt; / title&gt;  
&lt; / book&gt; 
&lt; / book_list&gt; 
&lt; book_list&gt; 
&lt; book&gt; 
&lt; author&gt; Bloggs&lt; / author&gt; 
&lt; title&gt;学习XML&lt; / title&gt; \  n&lt; / book&gt; 
&lt; book&gt; 
&lt; author&gt; Jones&lt; / author&gt; 
&lt; title&gt;从PHP开始&lt; / title&gt; 
&lt; / book&gt; 
&lt; / book_list&gt; \  n&lt; / inventory&gt; 
   
 
 

我怎样才能 book_list,循环遍历每本书,在php simplexml脚本中使用xpath? 这是我的代码,

  $ booklistpath = $ xml-&gt; xpath('// booklist'); 
 
foreach  ($ booklistpath as $ booklist){
 $ bookpath = $ xml-&gt; xpath('// book'); 
 foreach($ bookpath as $ book){
 ... 
} 
} \  n   
 
 

第一个循环很好,它遍历每个 book_list - 但是嵌套循环,意味着要经过每个 该特定 book_list 的书籍遍历整个文档中的每本书。 我也尝试过: -

 '。book 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();
        }
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题