dpa0760 2014-04-15 01:05
浏览 34
已采纳

PHP - 非常基本的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>
  • 写回答

1条回答 默认 最新

  • dongpo2458 2014-04-15 09:07
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行