PHP-非常基本的XMLReader [英] PHP - very basic XMLReader

查看:305
本文介绍了PHP-非常基本的XMLReader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为我将解析一个非常大的XML文件,所以我试图使用XMLReader来检索XML数据,并使用simpleXML进行显示.我从未使用过XMLreader,因此我只是想简单地了解使用XMLReader的基本知识.我想在XML文件中显示所有名称和价格值,但是我无法获取此代码以显示任何内容.我想念什么吗?

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?

这是XMLReader/simpleXML代码:

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

这是XML文件,名为 products.xml :

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>

推荐答案

您的循环条件已损坏.如果得到一个元素且该元素的名称为"product",则会循环. document元素为"products",因此循环条件决不会为TRUE.

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.

您必须知道read()next()正在移动内部光标.如果它在<product>节点上,则read()会将其移动到该节点的第一个子节点.

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

输出:

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

这篇关于PHP-非常基本的XMLReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆