simonnz Posted October 27, 2009 Share Posted October 27, 2009 Hello, I have sucessfull followed this tutorial http://www.phpfreaks.com/tutorial/handling-xml-data and used xpath to find the books I need, here is my code <?php // load SimpleXML $books = new SimpleXMLElement('books.xml', null, true); echo <<<EOF <table> <tr> <th>Title</th> <th>Author</th> <th>Publisher</th> <th>Price at Amazon.com</th> <th>ISBN</th> </tr> EOF; foreach($books->xpath('book1/book') as $book) // loop through our books { echo <<<EOF <tr> <td>{$book->title}</td> <td>{$book->author}</td> <td>{$book->publisher}</td> <td>\${$book->amazon_price}</td> <td>{$book['isbn']}</td> </tr> EOF; } echo '</table>'; ?> now I want to only show the first 5 books in the xml file as it is updated regularly I can't seem to figure out how to do this. any help would be great , thanks Link to comment https://forums.phpfreaks.com/topic/179160-solved-question-handling-xml-data/ Share on other sites More sharing options...
Bricktop Posted October 27, 2009 Share Posted October 27, 2009 Hi simonnz, Add a counter and then loop until 5 is reached. For example: <?php // load SimpleXML $books = new SimpleXMLElement('books.xml', null, true); echo <<<EOF <table> <tr> <th>Title</th> <th>Author</th> <th>Publisher</th> <th>Price at Amazon.com</th> <th>ISBN</th> </tr> EOF; //Defined the counter variable and set it to 1 $i = 1; foreach($books->xpath('book1/book') as $book) // loop through our books { //If the counter variable ($i) is less than or equal to 5 echo the result if($i <= 5){ echo <<<EOF <tr> <td>{$book->title}</td> <td>{$book->author}</td> <td>{$book->publisher}</td> <td>\${$book->amazon_price}</td> <td>{$book['isbn']}</td> </tr> EOF; } //Increment the counter variable ($i) by 1 $i++; } echo '</table>'; ?> Hope this helps. Link to comment https://forums.phpfreaks.com/topic/179160-solved-question-handling-xml-data/#findComment-945263 Share on other sites More sharing options...
simonnz Posted October 27, 2009 Author Share Posted October 27, 2009 perfect thanks Link to comment https://forums.phpfreaks.com/topic/179160-solved-question-handling-xml-data/#findComment-945273 Share on other sites More sharing options...
salathe Posted October 27, 2009 Share Posted October 27, 2009 SimpleXMLElement::xpath returns an array, so you could also as an alternative use array_slice() to get only the number of books that you want. Link to comment https://forums.phpfreaks.com/topic/179160-solved-question-handling-xml-data/#findComment-945331 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.