PHP SimpleXML-删除xpath节点

我对如何删除可以通过xpath搜索找到的东西的父节点有些困惑:


$xml = simplexml_load_file($filename);

$data = $xml->xpath('//items/info[item_id="' . $item_id . '"]');

$parent = $data[0]->xpath("parent::*");

unset($parent);

因此,它找到了项目ID,那里没有问题-但是未设置的项目并没有摆脱这个<items>节点。我要做的就是删除<items>...</items>此产品的。显然,<items>xml文件中有大量节点,因此它不能unset($xml->data->items)删除所有内容。


任何想法表示赞赏:-)


素胚勾勒不出你
浏览 464回答 3
3回答

当年话下

<?php$xml = new SimpleXMLElement('<a><b/></a>');unset($xml->b);echo $xml->asxml();由于调用了__unset()方法(或模块代码中的等效方法),因此可以按预期工作(从文档中删除<b />元素)。但是,当您调用unset($parent);它时,它只会删除存储在$ parent中的对象引用,但不会影响对象本身或$ xml中存储的文档。为此,我将恢复为DOMDocument。<?php$doc = new DOMDOcument;$doc->loadxml('<foo>&nbsp; <items>&nbsp; &nbsp; <info>&nbsp; &nbsp; &nbsp; <item_id>123</item_id>&nbsp; &nbsp; </info>&nbsp; </items>&nbsp; <items>&nbsp; &nbsp; <info>&nbsp; &nbsp; &nbsp; <item_id>456</item_id>&nbsp; &nbsp; </info>&nbsp; </items>&nbsp; <items>&nbsp; &nbsp; <info>&nbsp; &nbsp; &nbsp; <item_id>789</item_id>&nbsp; &nbsp; </info>&nbsp; </items></foo>');$item_id = 456;$xpath = new DOMXpath($doc);foreach($xpath->query('//items[info/item_id="' . $item_id . '"]') as $node) {&nbsp; $node->parentNode->removeChild($node);}echo $doc->savexml();版画<?xml version="1.0"?><foo>&nbsp; <items>&nbsp; &nbsp; <info>&nbsp; &nbsp; &nbsp; <item_id>123</item_id>&nbsp; &nbsp; </info>&nbsp; </items>&nbsp; <items>&nbsp; &nbsp; <info>&nbsp; &nbsp; &nbsp; <item_id>789</item_id>&nbsp; &nbsp; </info>&nbsp; </items></foo>
打开App,查看更多内容
随时随地看视频慕课网APP