douyan2970 2013-04-23 10:17
浏览 45

在PHP中删除XML节点

    $xmldoc = new DOMDocument();
    $xmldoc->load('card.xml');
    $root   = $xmldoc->documentElement;
    $fnode  = $root->firstChild;
    // we retrieve the chapter and remove it from the book
    $items = $xmldoc->getElementsByTagName('card');
    foreach ($items as $item){
        $node = $item->getElementsByTagName('cardnumber')->item(0);
        if ($node->nodeValue == $this->cardnumber){
            $node->parentNode->removeChild($node);
            $xmldoc->saveXML();
        }
    }

Above is the code I used to delete the card node if the card number is match, below is my XML format. But if failed to remove the card. Can anyone help?

<root>
  <card>
    <cardnumber>12345</cardnumber>
    <name>Tan</name>
  </card>
  ....
</root>
  • 写回答

3条回答 默认 最新

  • dongmu6225 2013-04-23 10:24
    关注

    The way you have removed the node is correct. But you to save it in an xml after saveXml() or you can just print the new xml and check for the update you have done. And also as per your logic save should be done after the loop. (i.e) as follows,

    $xmldoc = new DOMDocument();
    $xmldoc->load('card.xml');
    $root   = $xmldoc->documentElement;
    $fnode  = $root->firstChild;
    // we retrieve the chapter and remove it from the book
    $items = $xmldoc->getElementsByTagName('card');
    foreach ($items as $item){
        $node = $item->getElementsByTagName('cardnumber')->item(0);
        if ($node->nodeValue == $this->cardnumber){
            $node->parentNode->removeChild($node);            
        }
    }
    $xmldoc->save('newXmlFile.xml');
    

    (OR)

    print $xmldoc->saveXML();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services