Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
987 views
in Technique[技术] by (71.8m points)

xml - PHP - very basic XMLReader

Because I will be parsing a very large XML file, I am trying to use XMLReader to retrieve the XML data, and use simpleXML to display. I have never used XMLreader, so I am simply trying to get a basic feel for using XMLReader. I want to display all the name and price values in the XML file, and I cannot get this code to display anything. Am I missing something?

Here is the XMLReader/simpleXML code:

$z = new XMLReader;
$z->open('products.xml');
$doc = new DOMDocument;

while ($z->read() && $z->name === 'product') {
$node = simplexml_import_dom($doc->importNode($z->expand(), true));

var_dump($node->name);
$z->next('product');
}

Here is 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your loop condition is broken. You loop if you get an element AND that elements name is "product". The document element is "products", so the loop condition is never TRUE.

You have to be aware that read() and next() are moving the internal cursor. If it is on a <product> node, read() will move it to the first child of that node.

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

Output:

string(7) "Desktop"
string(14) " Desktop 1 (d)"
float(499.99)
string(6) "Tablet"
string(12) "Tablet 1 (t)"
float(1099.99)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...