用php删除xml文件中的子节点 [英] delete child node in xml file with php

查看:115
本文介绍了用php删除xml文件中的子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

?>

推荐答案

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

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

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

在旁注中,使用XPath时,您可以用更少的代码做到这一点:

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

将删除具有<id>子节点且具有存储在$id中的值的<record>元素.

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

在键盘上运行代码.

更多示例:从xml中删除元素

这篇关于用php删除xml文件中的子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆