开发者

delete child node in xml file with php

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");

?>


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜