0

i'm trying to remove a child node from an xml. my script is working..but it removing a few childs... and not just the one i want to remove...

can you look and tell me what is my problem?

The XML file:

<?xml version="1.0" encoding="UTF-8" ?> 
<events>
   <record>
      <id>3</id> 
   </record>
   <record>
      <id>2</id> 
   </record>
   <record>
      <id>1</id> 
   </record>
 </events>

The delete.php file:

<?php
header("Content-type: text/html; charset=utf-8");

$record = array(
    'id' => $_POST['id'],
);
$users = new DOMDocument();
$users->load("xmp.xml");

$suser = simplexml_load_file("xmp.xml");
$count = 0;
$user = $users->getElementsByTagName("record");

foreach($user as $value)
{
   $tasks = $value->getElementsByTagName("id");
   $task  = $tasks->item(0)->nodeValue;

   if ($task == $record["id"]) {
    $users->documentElement->removeChild($users->documentElement->childNodes->item($count));
   }
   $count++;
}

$users->save("xmp.xml");

?>
2
  • why is this line in the code: $suser = simplexml_load_file("xmp.xml");? Commented Jan 12, 2011 at 10:20
  • Hmm.. i have no idea.. it's mistake.. Commented Jan 12, 2011 at 10:27

1 Answer 1

3

Fetch the node you want to remove. Call removeChild() on it's parentNode, e.g.

$node->parentNode->removeChild($node);

On a sidenote, you can do this with less code when using XPath:

$id  = /* some integer value */ 
$dom = new DOMDocument;
$dom->load('file.xml');
$xpath = new DOMXPath($dom);
$query = sprintf('/events/record[./id = "%d"]', $id);
foreach($xpath->query($query) as $record) {
    $record->parentNode->removeChild($record);
}
echo $dom->saveXml();

will remove the <record> element with an <id> child node having the value stored in $id.

Run code on Codepad.

More examples: remove element from xml

Sign up to request clarification or add additional context in comments.

3 Comments

can you be more detailed? Where should i put this line in my script?
@Ofear instead of your removeChild call.
This is great! Works perfect!! can you please add in the first line $id = "some integer number" ; for others who will look for answer? Thanks you very much gordon!

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.