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.
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":
Example of removing a child element with a specific attribute in SimpleXML for PHP using the XPath() function
<?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);
}
// 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 using a reference (&$node), which is required for the unset() function to modify the original XML tree. Calling unset($node) removes the matched element itself, rather than its children.