2

my product.xml :

<product>
    <name></name>
    <price></price>
    <short_desc></short_desc>
    <quantity></quantity>
</product>

how i can split xml data to many page, let's say i have 30 record of product and i want it to show 5 per page, so then i have 6 page in the same 1 file.php.

i was read to split to pages but it doesn't work, anyone can help me?

    $objDOM = new DOMDocument();
    $objDOM->load("product.xml");

    $titleArray = array();

    $ps = $objDOM->getElementsByTagName("product");

    $allItems = array(
          "name" => $node->getElementsByTagName("name")->item(0)->nodeValue,
          "rice" => $node->getElementsByTagName("price")->item(0)->nodeValue,
          "short_desc" => $node->getElementsByTagName("short_desc")->item(0)->nodeValue,
          "quantity" => $node->getElementsByTagName("quantity")->item(0)->nodeValue);

    $itemsPerPage = 5;
        $page = isset($_GET['page']) ? intval($_GET['page']) : 0;

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

this is what i have doing but it doesn't show anything,,

4

2 回答 2

0

您可以使用 simplexml_load_string 或 simplexml_load_file 函数(来自 php 5)吗?如果您的 product.xml 文件具有简单的结构,您可以使用以下代码轻松地做您想做的事情:

$allItems = simplexml_load_file("product.xml");
$itemsPerPage = 5;
$page = isset($_GET['page']) ? intval($_GET['page']) : 0;

$pageItems = array_slice($allItems, $page * $itemsPerPage, $page * $itemsPerPage + $itemsPerPage)

foreach($allItems AS $prod) {
  echo $prod->name."<br>";
  echo $prod->price."<br>";
  echo $prod->short_desc."<br>";
  echo $prod->quantity."<br>";
  echo "---------<br>";
}

另外,检查您的 XML 文件:它必须以 xml 声明和根元素开头!

<?xml version='1.0'?>
<products>
  <product>
    <name>name1</name>
    <price>price1</price>
    <short_desc>desc1</short_desc>
    <quantity>q1</quantity>
  </product>
  <product>
    <name>name2</name>
    <price>price2</price>
    <short_desc>desc2</short_desc>
    <quantity>q2</quantity>
  </product>
  <product>
    <name>name3</name>
    <price>price3</price>
    <short_desc>desc3</short_desc>
    <quantity>q3</quantity>
  </product>
</products>
于 2013-10-12T19:15:58.267 回答
0

我不会将所有产品都变成一个数组,而是首先利用您正在使用的 DOMDocument 提供对单个元素和数据的访问这一事实。

在以下示例中,通过使用 DOMDocuments DOMXpath 对象和LimitIterator. 您可以找到使用 SimpleXML 的以下答案的完整示例:

下面是同样适用于 DOMDocument 和 DOMXPath 的用法示例:

$doc = new DOMDocument();
$doc->loadXML($xml);

$xpath    = new DOMXPath($doc);
$products = $xpath->query('/xml/product');

$_GET['page'] = 3;
$itemsPerPage = 2;

$pagination = new LimitPagination(
    defaultvar($_GET, 'page'), $products->length, $itemsPerPage
);

foreach ($pagination->getLimitIterator($products) as $product) {
    /* @var $product DOMElement */
    echo $product->ownerDocument->saveXML($product), "\n";
}

您可以在此处找到完整的、自包含的示例代码(包括 XML):https ://gist.github.com/hakre/603638a18918b0549019

于 2013-10-13T17:33:03.450 回答