I have several identical elements with different attributes that I’m accessing with SimpleXML:
<data> <seg id='A1'/> <seg id='A5'/> <seg id='A12'/> <seg id='A29'/> <seg id='A30'/> </data>
I need to remove a specific seg element, with an id of ‘A12’, how can I do this? I’ve tried looping through the seg elements and unsetting the specific one, but this doesn’t work, the elements remain.
foreach($doc->seg as $seg) { if($seg['id'] == 'A12') { unset($seg); } }
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
SimpleXMLElementinto aDOMElement.Just some example code (tested with PHP 5.2.5):
outputs
By the way: selecting specific nodes is much more simple when you use XPath (SimpleXMLElement->xpath):