PHP-删除XML元素 [英] PHP - Delete XML Element

查看:59
本文介绍了PHP-删除XML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用PHP删除XML文件的元素.这将通过ajax完成,我需要通过属性来找到XML元素.

I need to delete elements of an XML file using PHP. It will be done via ajax and I need to find the XML element via an attribute.

这是我的XML文件

<?xml version="1.0" encoding="utf-8"?>
<messages>
    <message time="1248083538">
        <name>Ben</name>
        <email>Ben's Email</email>
        <msg>Bens message</msg>
    </message>
    <message time="1248083838">
        <name>John Smith</name>
        <email>john@smith.com</email>
        <msg>Can you do this for me?</msg>
    </message>
</messages>

所以我要说的是删除时间等于1248083838的元素.

So what I would say is something like delete the element where the time equals 1248083838.

到目前为止,我一直在使用Simple XML,但我刚刚意识到它可以完成除delete元素之外的所有操作.

Ive been using Simple XML up until now and I've just realised it can do everything except delete elements.

那我该怎么做?

推荐答案

您可以在PHP中使用DOM类. ( http://us3.php.net/manual/en/intro.dom. php ).

You can use the DOM classes in PHP. ( http://us3.php.net/manual/en/intro.dom.php ).

您将需要将XML文档读入内存,使用DOM类进行操作,然后可以根据需要保存XML(保存到http或文件).

You will need to read the XML document into memory, use the DOM classes to do manipulation, and then you can save out the XML as needed (to http or to file).

DOMNode是其中具有删除功能(以解决您的问题)的对象.

DOMNode is an object in there that has remove features (to address your question).

它比SimpleXML复杂一点,但是一旦您习惯了它,它的功能就会强大得多

It's a little more complicated than SimpleXML but once you get used to it, it's much more powerful

(半取自php.net的代码示例)

(semi-taken from a code example at php.net)

<?php

$doc = new DOMDocument; 
$doc->load('theFile.xml');

$thedocument = $doc->documentElement;

//this gives you a list of the messages
$list = $thedocument->getElementsByTagName('message');

//figure out which ones you want -- assign it to a variable (ie: $nodeToRemove )
$nodeToRemove = null;
foreach ($list as $domElement){
  $attrValue = $domElement->getAttribute('time');
  if ($attrValue == 'VALUEYOUCAREABOUT') {
    $nodeToRemove = $domElement; //will only remember last one- but this is just an example :)
  }
}

//Now remove it.
if ($nodeToRemove != null)
$thedocument->removeChild($nodeToRemove);

echo $doc->saveXML(); 
?>

这应该使您对如何删除元素有一些了解.它将在没有该节点的情况下打印出XML.如果要将其发送到文件,只需将字符串写入文件.

This should give you a little bit of an idea on how to remove the element. It will print out the XML without that node. If you wanted to send it to file, just write the string to file.

这篇关于PHP-删除XML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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