Question

How can I delete specific elements on xml using php

my.xml

    <usr>
        <uid trk= "1234">
            <deleteThis>
                <mychild>here</mychild>
                <anotherchild>here</anotherchild>
            </deleteThis>
        </uid>
    </usr>

I want to remove the "deleteThis" element and its children

result:

     <usr>
        <uid trk= "1234">
        </uid>
    </usr>

here's my non-working code

index.php

$xml = new DOMDocument; 
    $xml->load('my.xml');
    $thedocument = $xml->documentElement;
    $list = $thedocument->getElementsByTagName('uid');

    foreach ($list as $domElement){
      $attrValue = $domElement->getAttribute('trk'); 
      if ($attrValue == "1234") { //if <uid trk= "1234">
        $valY = $domElement->getElementsByTagName('deleteThis');
        $thedocument->removeChild($valY);
      }
    }
$xml->save("my.xml");

It seems it doesn't found the node.

Was it helpful?

Solution

  if ($attrValue == "1234") { //if <uid trk= "1234">
    $valY = $domElement->getElementsByTagName('deleteThis');
    //$valY is a DOMNodeList, that you happen to know there is only one doesnt matter
    foreach($valY as  $delnode){
      $delnode->parentNode->removeChild( $delnode);
    }
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top