使用php删除xml文件中的子节点

时间:2011-01-12 10:01:55

标签: php xml

我正在尝试从xml中删除子节点。  我的脚本正在工作..但它删除了几个孩子...而不仅仅是我要删除的那个......

你可以看一下,告诉我我的问题是什么吗?

XML文件:

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

delete.php文件:

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

?>

1 个答案:

答案 0 :(得分:3)

获取要删除的节点。在removeChild()上调用parentNode,例如

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

在旁注中,使用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();

将删除<record>元素,其中<id>子节点的值存储在$id中。

Run code on Codepad

更多示例:remove element from xml