質問

The XMLReader/Xpath code below works fine WITHOUT the if statement (in the second while loop). When the if statement is put in, the page doesn't even load. Any advice on what is wrong with the if statement? Thanks!

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

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

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

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

$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');
}}

Here is a bit code of the XML file, named products.xml:

<products>

<product category="Desktop">
<name> Desktop 1 (d)</name>
<price>499.99</price>
</product>

<product category="Tablet">
<name>Tablet 1 (t)</name>
<price>1099.99</price>
</product>

</products>
役に立ちましたか?

解決

The position of $reader->next('product'); is wrong. It should be out of the first brace.

i.e.

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

to

}
$reader->next('product');
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top