php and xpath - loop through child elements of particular element
php, simplexml, xpath
Solution
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();
}
}
Problem
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' ```