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条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog