Simplexml - Remove Xpath Node

Deleting simplexmlelement node

Use unset(): Remove a child with a specific attribute, in SimpleXML for PHP

Delete a node with simplexml in php

Load the file using simplexml_load_file(), loop through the <server> nodes and check if the IP is equal to the given IP.

If it is, use unset() on the self-reference of the SimpleXMLElement node to remove it:

$xml = simplexml_load_file('file.xml');
foreach ($xml as $key => $server) {
if ( $server->ip != '192.168.0.1') {
continue;
}
unset($server[0]);
}

Demo.

Delete XML node with SimpleXML, PHP

Use xpath to find a node. With your example it will be

//a[name="A1"]/b[2]

and use DomDocument method removeChild to change xml

$sxe = simplexml_load_string($xml);
$node = $sxe->xpath('//a[name="'. $ID .'"]/b['. $num .']');
$dom=dom_import_simplexml($node[0]);
$dom->parentNode->removeChild($dom);
echo $sxe->asXML();

Remove a child with a specific attribute, in SimpleXML for PHP

While SimpleXML provides a way to remove XML nodes, its modification capabilities are somewhat limited. One other solution is to resort to using the DOM extension. dom_import_simplexml() will help you with converting your SimpleXMLElement into a DOMElement.

Just some example code (tested with PHP 5.2.5):

$data='<data>
<seg id="A1"/>
<seg id="A5"/>
<seg id="A12"/>
<seg id="A29"/>
<seg id="A30"/>
</data>';
$doc=new SimpleXMLElement($data);
foreach($doc->seg as $seg)
{
if($seg['id'] == 'A12') {
$dom=dom_import_simplexml($seg);
$dom->parentNode->removeChild($dom);
}
}
echo $doc->asXml();

outputs

<?xml version="1.0"?>
<data><seg id="A1"/><seg id="A5"/><seg id="A29"/><seg id="A30"/></data>

By the way: selecting specific nodes is much more simple when you use XPath (SimpleXMLElement->xpath):

$segs=$doc->xpath('//seq[@id="A12"]');
if (count($segs)>=1) {
$seg=$segs[0];
}
// same deletion procedure as above

deleting xml node using SimpleXmlElement

use

unset($items[$index][0]);

There is a very good explanation on why this is working this way on SO by hakre, look it up.

Apart from that, you could simplify your code and do everything in just 3 lines:

$xml = simplexml_load_string($x); // assume XML in $x
$items = $xml->xpath("/items/item[qty='0' and qtyonhold='0']");
foreach ($items as $item) unset($item[0]);
  • that xpath selects all <item>-nodes with both 0 in their children <qty> and <qtyonhold>
  • loop through the array $items with foreach and use the unset-syntax explained above.

see it working: http://codepad.viper-7.com/Hae4vY

How to delete xml element if it's empty simplexml

1st) close the tag because now your xml is not loaded by Dom parser

2nd) change this line node->$inst_child->module->removeChild($node); to

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

3rd) add echo to the last line to see the result

Here working code



Related Topics



Leave a reply



Submit