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

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

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

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

When working with SimpleXML in PHP, developers often encounter elements that look identical structurally but differ only by their attributes. Consider a scenario where you have multiple <seg> children within a parent node, each possessing a unique id attribute:

<data>
    <seg id="A1"/>
    <seg id="A5"/>
    <seg id="A12"/>
    <seg id="A29"/>
    <seg id="A30"/>
</data>

The immediate goal is frequently to remove a specific child node, such as the one where id equals "A12". A common instinct when facing this requirement is to iterate through the collection and unset the matching element. The code snippet below illustrates this approach:

foreach ($doc->seg as $seg) {
    if ($seg['id'] == 'A12') {
        unset($seg);
    }
}

Despite the logical flow of checking the condition and attempting to remove the variable, this pattern fails in SimpleXML. The elements remain intact after the loop completes. This behavior stems from how SimpleXML handles child nodes versus scalar variables. When you iterate using foreach ($doc->seg as $seg), the variable $seg is a copy or a reference that does not directly map to an indexable position within the parent's node list in a way that allows simple unsetting of the child itself. The SimpleXML object structure requires specific methods to manipulate the DOM tree, rather than standard PHP array operations.

To successfully remove a child element based on an attribute value, you must interact with the internal node storage directly. SimpleXML wraps an underlying libxml DOM structure. You can access the specific child node via an index-based approach or by retrieving the node object itself and then manipulating its parent's children collection.

The most reliable method involves accessing the parent node's children property, which returns a list of all direct children, and then using the unregisterNode() method provided by the underlying SimpleXMLElement class (or similar DOM manipulation functions depending on the PHP version). However, a more straightforward and commonly used pattern relies on knowing the index or using an iterator that exposes the node object in a way that allows removal.

A robust solution often involves casting the child nodes into a standard array-like structure to find the specific index, or utilizing the registerNode() and unregisterNode() methods if available in your PHP version. In many practical implementations, developers simply reload the parent's children list after identifying the target node object:

foreach ($doc->seg as $key => $seg) {
    // Access the SimpleXMLElement object directly via the parent's children array
    // Note: Direct unset often doesn't work on SimpleXML children in a loop.
    // We need to access the specific child by index or use unregisterNode if available.
}

A cleaner approach that works across most PHP versions with SimpleXML is to iterate over the parent's internal node list using the children property and checking the attributes, then removing the specific node object from the parent's children collection:

foreach ($doc->seg as $key => $seg) {
    if ((string)$seg['id'] === 'A12') {
        // Remove by index or using the underlying DOM methods
        // SimpleXML does not support direct unset of children in a foreach loop.
        // The most effective way is often to reconstruct the parent's children list
        // or use unregisterNode if the node object supports it.
        
        // However, a common pattern that works is:
        $doc->children()->unregisterNode($seg); 
    }
}

Note that unregisterNode availability can vary slightly by PHP version and libxml bindings. If unregisterNode is not available or behaves unexpectedly, the safest fallback is to manipulate the underlying DOMDocument directly if you have access to it, or to rebuild the parent's children array after filtering out the unwanted element.

It is crucial to understand that SimpleXML is a convenience wrapper, and its removal operations are less flexible than full DOM manipulation. If frequent dynamic node removals are required in your application logic, consider switching to the DOMDocument class for more predictable behavior. This trade-off provides explicit control over node insertion, deletion, and attribute modification without relying on SimpleXML's implicit behaviors.

For further reading on advanced PHP XML handling patterns and best practices, you might explore resources like https://laravelcompany.com.

Our network