Jump to content

[SOLVED] Question handling xml data


simonnz

Recommended Posts

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 ;D

Link to comment
https://forums.phpfreaks.com/topic/179160-solved-question-handling-xml-data/
Share on other sites

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.