【问题标题】:PHP - multiple while loops from a single parse with XMLReaderPHP - 使用 XMLReader 进行一次解析的多个 while 循环
【发布时间】: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


    【解决方案1】:

    据我了解 XmlReader API 它只能向前工作,一旦你解析了一个节点,你就不能回去了。因此,如果您有一个 while 循环消耗所有 product 元素,则第二个循环将无法找到更多这些元素,因为当第二个循环开始时,阅读器位于最后一个 product 元素之后。 SimpleXML 不同,我认为它会构建一棵树,因此您可以在需要时返回并多次读取节点。如果您想使用 XmlReader API,那么您必须编写一个循环来读取 product 元素并缓冲您想要稍后输出或在不同位置输出的数据。

    【讨论】:

      猜你喜欢
      • 2012-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-01
      • 2014-12-18
      • 2016-12-28
      相关资源
      最近更新 更多