【发布时间】:2014-06-03 23:15:44
【问题描述】:
使用 XMLReader,我尝试仅解析一次非常大的 XML,但在一次解析 XML 文件时使用多个 while 循环,如下所示。那可能吗?只解析一次大文件似乎可以节省开销和内存消耗。
$reader = new XMLReader;
$reader->open('products.xml');
$dom = new DOMDocument;
$xpath = new DOMXpath($dom);
while ($reader->read() && $reader->name !== 'product') {
continue;
}
这个while循环正确执行并用值填充数组
while ($reader->name === 'product') {
$node = $dom->importNode($reader->expand(), TRUE);
if ($xpath->evaluate('number(price)', $node) > $price_submitted) {
$name = $xpath->evaluate('string(name)', $node);
$nameArray[] = $name;
}
$reader->next('product');
}
这个 while 循环没有正确执行,没有回显,这需要在一个单独的 while 循环中完成,以便显示目的
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);
echo "Category: " . $category . ". ";
echo "Name: " . $name . ". ";
echo "Price: " . $price . ". ";
echo "<br>";
}
$reader->next('product');
}
使用 simpleXML,您可以从文件的单个解析中使用多个 foreach 循环,我正在尝试使用上面的 XMLReader。
foreach($XMLproducts->product as $Product) {
if ($Product->price > $price_submitted) {
$nameArray[] = $name;
}}
foreach($XMLproducts->product as $Product) {
if ($Product->price > $price_submitted) {
echo $Product->name . " " . $Product->price
}}
【问题讨论】:
标签: php xpath simplexml xmlreader