dss67853
2018-05-29 04:17
浏览 74

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

相关推荐 更多相似问题