dss67853 2018-05-29 04:17
浏览 75
已采纳

PHP按属性删除XML节点

Have tried numerous examples on SO but none have worked.

Goal: Remove a node (unit) and it's children, by specific id=

filename.xml

<archive>
  <unit id="0424670018">
    <data>Blah blah blah #1</data>
    <gdate>2018-05-28 00:42:46</gdate>
</unit>
  <unit id="0450170018">
    <data>Blah blah blah #2</data>
    <gdate>2018-05-28 00:45:01</gdate>
  </unit>
</archive>

Code used, not sure why it does not work when loaded:

$id = '0450170018';
$file = 'filename.xml';
$xml = simplexml_load_string($file);

foreach($xml->archive as $fileload){
    if($fileload->unit['@id'] == $id){
        $dom = dom_import_simplexml($fileload);
        $dom->parentNode->removeChild($dom);
    }
}
  • 写回答

2条回答 默认 最新

  • doupo2157 2018-05-29 17:17
    关注

    You can fetch the node using Xpath. It allows to fetch the matching node(s) directly.

    $id = '0450170018';
    
    $document = new DOMDocument();
    $document->load('filename.xml');
    $xpath = new DOMXpath($document);
    foreach ($xpath->evaluate("//unit[@id='$id']") as $unitNode) {
      $unitNode->parentNode->removeChild($unitNode);
    }
    $document->save('filename.xml');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥21 matlab怎么求时域信号的二阶导数
  • ¥15 判断两个表是否完全相同
  • ¥15 java map类型数据格式,如何快速通过前缀匹配元素
  • ¥15 stc12c5a60s2、QMC5883L、LCD1602组合测量磁场所需程序
  • ¥15 vba参数转c++ SAFEARRAY
  • ¥20 Win11测试yolov4,“找不到nvcuda.dll”怎么办?
  • ¥15 simulink绘制bode图
  • ¥15 php_network_getaddresses: getaddrinfo failed: Name or service not known
  • ¥15 用msg发消息出现的问题
  • ¥15 unity3d机械臂