[英]xml find nodes parent and delete simplexml php
how do I delete a parent node with php in xml and save changes 如何在xml中使用php删除父节点并保存更改
what I try 我尝试
<element>
<feed id=" 9 ">
<title>test</title>
<table>feeds</table>
<link/>
<feed_type>API</feed_type>
<affiliate/>
<mwst>ja</mwst>
<tld>DE</tld>
<query/>
</feed>
</element>
public function deleteNode($feed_id){
//find feed on attribute ID
$node = $this->xml->xpath('//feed[@id =' . $feed_id . ' ]');
//find the parent and delete thenode
$element = $node[0]->xpath('parent::*');
// ??unset($element[0]);
$this->xml->asXML(SITE_ROOT . '/xml/feed_config.xml');
exit();
}
Edit #1: 编辑 #1:
(Thanks to @michi for pointing out that unset
is sufficient to delete a node in SimpleXML) (感谢@michi指出未
unset
足以删除SimpleXML中的节点)
If you want to remove <element>
, not <feed>
as I previously thought, you can do this: 如果要删除
<element>
,而不是我以前认为的<feed>
,可以这样做:
function deleteNode($feed_id)
{
$parent=$this->xml->xpath('//*[feed[@id=" '.$feed_id.' "]]');
unset($parent[0][0]);
}
Online demo 在线演示
(Works for PHP>=5.2.2) (适用于PHP> = 5.2.2的作品)
Original post 原始帖子
You might need DOM for this: 您可能需要DOM :
function deleteNode($feed_id)
{
$node=$this->xml->xpath('//feed[@id=" '.$feed_id.' "]');
$node=dom_import_simplexml($node[0]);
$parent=$node->parentNode;
$parent->removeChild($node);
$this->xml=simplexml_import_dom($parent->ownerDocument);
}
Online demo 在线演示
(Noted that since it's not in a class in the demo, I used a global
for the purpose of lazy emulation. Avoid global
in your actual code.) (请注意,由于它不在演示的类中,因此我使用了
global
变量来进行懒惰仿真。请在实际代码中避免使用global
变量。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.