Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
缓冲或移动PHP数据以显示在网页的不同部分_Php_Xpath_Xmlreader_Buffering - Fatal编程技术网

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

缓冲或移动PHP数据以显示在网页的不同部分,php,xpath,xmlreader,buffering,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循环用于根据用户输入显示相关数据,以及使用

我正在用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循环中构建的数组。我需要在上面的while循环显示相关搜索结果之前,在下面的foreach循环中显示这些值。使用XMLReader,每次解析XML时只能执行一个while循环,由于内存和开销问题,我不想解析它两次。最好的方法是什么

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

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

<?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或文件支持的临时存储

谢谢!每页只会有10到20个搜索结果,其中包含类别、名称和其他一些变量以及缩略图,所以内存可能不会有问题。我一直在玩弄缓冲功能,即ob_start;ob_end_冲洗;但却没能让它发挥作用。你会考虑缓冲一个选项吗?缓冲也会起作用,但是缓冲将需要更多的内存,所以我没有建议。我会做的有点不同:1。ob_启动;2. $contents=ob_get_flush;3.foreach{…}4 echo$内容;