缓冲或移动PHP数据以显示在网页的不同部分

时间:2014-04-19 18:09:52

标签: php xpath xmlreader buffering

我正在使用XMLReader解析一个非常大的XML文件。

$reader = new XMLReader;
$reader->open('products.xml');
$dom = new DOMDocument;
$xpath = new DOMXpath($dom);

while ($reader->read() && $reader->name !== 'product') {
continue;
}

while循环用于根据用户输入显示相关数据,以及使用XML值构建数组。

while ($reader->name === 'product') {
$node = $dom->importNode($reader->expand(), TRUE);

if ($xpath->evaluate('number(price)', $node) > $price_submitted) {

$category = $xpath->evaluate('string(@category)', $node);
$name = $xpath->evaluate('string(name)', $node);
$price = $xpath->evaluate('number(price)', $node);

// Relevant search results displayed here:
echo "Category: " . $category . ". ";
echo "Name: " . $name . ". ";
echo "Price: " . $price . ". ";


$nameArray[] = $name;

}
$reader->next('product');
}

下面的foreach循环使用上面while循环中构建的数组。我需要这些值(在下面的foreach循环中显示)出现在上面的while循环之前显示相关的搜索结果。使用XMLReader,每次解析XML时都只能执行一个while循环,而且由于内存和开销问题,我不想解析它两次。这样做的最佳方式是什么?

foreach ($nameArray as $names) {
echo $names . " "; 
}

1 个答案:

答案 0 :(得分:0)

嗯......没有太多选择。最有效的直接方法是将类别/名称/价格存储在数组中,而不是直接输出:

<?php
$data = array();
while ($reader->name === 'product') {
    $node = $dom->importNode($reader->expand(), TRUE);

    if ($xpath->evaluate('number(price)', $node) > $price_submitted) {
        $category = $xpath->evaluate('string(@category)', $node);
        $name = $xpath->evaluate('string(name)', $node);
        $price = $xpath->evaluate('number(price)', $node);

        $data[] = array($category, $name, $price);
        $nameArray[] = $name;
    }

    $reader->next('product');
}

foreach ($nameArray as $names) {
    echo $names . " "; 
}

foreach ($data as $datum) {
    // Relevant search results displayed here:
    echo "Category: " . $datum[0] . ". ";
    echo "Name: " . $datum[1] . ". ";
    echo "Price: " . $datum[2] . ". ";
}

如果内存不起作用(您提到XML文件非常大),您应该使用db或文件支持的临时存储