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.

3
  • 2
    This SO answer should help you: stackoverflow.com/questions/3602207/… Commented Jan 12, 2012 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. Commented Jan 12, 2012 at 22:58
  • @rdlowrey By the way I made some changes, and it works with the help of yours. tnx. :) Commented Jan 12, 2012 at 23:11

1 Answer 1

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);
    }
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I already done that with the help on the top. Thanks by the way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.