Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.