你的循环条件被破坏了.如果你得到一个元素并且元素名称是“product”,则循环.文档元素是“products”,因此循环条件永远不会为TRUE.
您必须知道read()和next()正在移动内部游标.如果它在< product>上node,read()会将其移动到该节点的第一个子节点.
$reader = new XMLReader;
$reader->open($file);
$dom = new DOMDocument;
$xpath = new DOMXpath($dom);
// look for the first product element
while ($reader->read() && $reader->localName !== 'product') {
continue;
}
// while you have an product element
while ($reader->localName === 'product') {
$node = $reader->expand($dom);
var_dump(
$xpath->evaluate('string(@category)', $node),
$xpath->evaluate('string(name)', $node),
$xpath->evaluate('number(price)', $node)
);
// move to the next product sibling
$reader->next('product');
}
输出:
string(7) "Desktop"
string(14) " Desktop 1 (d)"
float(499.99)
string(6) "Tablet"
string(12) "Tablet 1 (t)"
float(1099.99)