首页 > 解决方案 > Php remove node from xml containing string

问题描述

I have an XMl file with url nodes. I need to find url node containing the word "Server" and remove them from the file.

<?php    
    $document = new DOMDocument();
    $document->load("../xml/cars689737484897767756.xml"); 
    $xpath = new DOMXpath($document); 
    foreach ($xpath->query('.//images[contains(., "Server")]') as $dataNode) {
      $dataNode->parentNode->removeChild($dataNode);
    }
     $document->saveXML();
?>

It does not save the removed node.

标签: phpxml

解决方案


$document->saveXML();返回结果字符串。您需要以您需要的方式处理该结果。一种方法可能是file_put_contents()

file_put_contents('/path/to/file.xml', $document->saveXML());

或者你也可以DOMDocument::save()像这样使用:

$document->save('/path/to/file.xml');

但前者提供了更多控制权,因为可以选择要转储的节点。


推荐阅读