1

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.

Robin Carlo Catacutan
  • 13,249
  • 11
  • 52
  • 85
  • 2
    This SO answer should help you: http://stackoverflow.com/questions/3602207/php-cant-remove-node-from-domdocument –  Jan 12 '12 at 22:48
  • @rdlowrey Tnx for the fast response, but still doesn't. If removing the 1st and 2nd element that should work, but going deeper on the third element it doesn't. I don't know what should be done here. – Robin Carlo Catacutan Jan 12 '12 at 22:58
  • @rdlowrey By the way I made some changes, and it works with the help of yours. tnx. :) – Robin Carlo Catacutan Jan 12 '12 at 23:11

1 Answers1

3
  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);
    }
  }
Wrikken
  • 69,272
  • 8
  • 97
  • 136