用PHP的XML分页[复制](XML pagination with PHP [duplicate]

2019-08-18 06:51发布

这个问题已经在这里有一个答案:

  • 如何分页在foreach循环与PHP线 2个回答

下面是我使用的解析XML文件中的代码,但文件中有许多记录,我想它分页,并显示20条记录每页。

我也想在页面底部分页链接,这样用户可以去其他网页也是如此。 它应该是这样的,如果没有价值就是给那么它将开始从0到20否则,如果值是40 2开始,并在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>";
}

Answer 1:

像这样的东西应该工作:

<?php
    $startPage = $_GET['page'];
    $perPage = 10;
    $currentRecord = 0;
    $xml = new SimpleXMLElement('xmlfile.xml', 0, true);

      foreach($xml->product as $key => $value)
        {
         $currentRecord += 1;
         if($currentRecord > ($startPage * $perPage) && $currentRecord < ($startPage * $perPage + $perPage)){

        echo "<a href=\"http://www.example.org/test/test1.php?sku={$value->sku}\">$value->name</a>";    

        //echo $value->name;

        echo "<br>";

        }
        }
//and the pagination:
        for ($i = 1; $i <= ($currentRecord / $perPage); $i++) {
           echo("<a href='thispage.php?page=".$i."'>".$i."</a>");
        } ?>


Answer 2:

你可以使用PHP的array_slice功能(文档: http://www.php.net/manual/en/function.array-slice.php )

开始是$page * $itemsPerPage ,年底将是$page * $itemsPerPage + $itemsPerPage和页数将ceil(count($xml->product) / $itemsPerPage)

例:

$allItems = array(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
$itemsPerPage = 5;
$page = isset($_GET['page']) ? intval($_GET['page']) : 0;

foreach (array_slice($allItems, $page * $itemsPerPage, $page * $itemsPerPage + $itemsPerPage) as $item) {
    echo "item $item";
}

它甚至:)看到: http://codepad.org/JiOiWcD1



Answer 3:

作为SimpleXMLElement是一个Traversable ,你可以做一个分页LimitItertor附带的PHP。

为了让您可以使用该产品元素总数SimpleXMLElement::count()函数。

分页的工作原理是在数以百计的其他问题,概括,我最好使用LimitPagination类型吧。

这需要在当前页面,元件和元件每页作为参数的总量(参见,以及: PHP 5.2和分页 )。 它也有一个辅助功能,能够为LimitIterator

例:

$products = $xml->product;

// pagination
$pagination = new LimitPagination($_GET['page'], $products->count(), 20);

foreach ($pagination->getLimitIterator($products) as $product) {
    ...
}

如果你想输出一个寻呼机,允许网页间导航时, LimitPagination有更多的提供,以一个更容易一点,例如,对于刚刚凸显当前页面(这里示范带支架)的所有页面:

foreach ($pagination->getPageRange() as $page)
{
    if ($page === $pagination->getPage()) {
        // current page
        printf("[p%d] ", $page); 
    } else {
        printf("p%d ", $page);
    }
}

foreach ($pagination->getPageRange() as $page)
{
    if ($page === $pagination->getPage()) {
        // current page
        printf("[p%d] ", $page); 
    } else {
        printf("p%d ", $page);
    }
}

互动在线演示: http://codepad.viper-7.com/OjvNcO
少交互式在线演示: http://eval.in/14176



文章来源: XML pagination with PHP [duplicate]