This question already has an answer here:
Below is code I'm using to parse XML file, however file has many records and I want to paginate it, and display 20 records per page.
I also want the pagination links at bottom of page so users can go to other pages as well. It should be something like, if no value is give then it will start from 0 to 20 else if value is 2 start from 40 and stop at 60, test.php?page=2
.
$xml = new SimpleXMLElement('xmlfile.xml', 0, true);
foreach ($xml->product as $key => $value) {
echo "<a href=\"http://www.example.org/test/test1.php?sku={$value->sku}\">$value->name</a>";
echo "<br>";
}
As
SimpleXMLElement
is aTraversable
, you can do the pagination with aLimitItertor
which ships with PHP.To get the total number of product elements you can use the
SimpleXMLElement::count()
function.Pagination works like outlined in the hundreds of other questions, I preferable use the
LimitPagination
type for it.It takes the current page, the total amount of elements and elements per page as arguments (see as well: PHP 5.2 and Pagination). It also has a helper function to provide the
LimitIterator
.Example:
If you want to output a pager that allows to navigate between the pages, the
LimitPagination
has more to offer to make that a bit easier, e.g. for just all pages highlighting the current page (here exemplary with brackets):Interactive online demo: http://codepad.viper-7.com/OjvNcO
Less interactive online demo: http://eval.in/14176
You could use php's
array_slice
function (Documentation: http://www.php.net/manual/en/function.array-slice.php)Start would be
$page * $itemsPerPage
, end would be$page * $itemsPerPage + $itemsPerPage
and the number of pages would beceil(count($xml->product) / $itemsPerPage)
.Example:
It even works :) see: http://codepad.org/JiOiWcD1
Something like this should work: