Remove a child with a specific attribute, in SimpleXML for PHP
You can remove a child element with a specific attribute in SimpleXML for PHP using the xpath()
function. The xpath()
function allows you to search for elements that match a specific XPath expression.
Here is an example of how you can remove a child element with the attribute "id" equal to "123":
<?php
// XML string
$xml_string = "<root>
<node id='111'>Node 111</node>
<node id='123'>Node 123</node>
<node id='456'>Node 456</node>
</root>";
// Load the XML string into a SimpleXMLElement object
$xml = simplexml_load_string($xml_string);
// Use the xpath() method to search for a node with the id attribute equal to "123"
foreach ($xml->xpath("//*[@id='123']") as $node) {
// Use the unset() function to remove the node
unset($node[0]);
}
// Convert the SimpleXMLElement object back to an XML string
$new_xml_string = $xml->asXML();
// Output the modified XML string
echo $new_xml_string;
?>
This code loads an XML string into a SimpleXML object, then uses the xpath()
function to search for all elements with an "id" attribute equal to "123". The foreach loop iterates through the resulting nodes, and the unset
function is used to remove each node from the XML tree.