Home >Backend Development >PHP Tutorial >How to Remove a Specific Child Element with a Given Attribute in SimpleXML Using PHP?

How to Remove a Specific Child Element with a Given Attribute in SimpleXML Using PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-15 13:46:20286browse

How to Remove a Specific Child Element with a Given Attribute in SimpleXML Using PHP?

Removing Specific Children with Attributes Using PHP's SimpleXML

In SimpleXML, directly removing child elements using unset() may not be effective. To eliminate a specific child with a particular attribute (e.g., an element with an id of "A12"), consider employing the DOM extension.

Solution Using DOM

  1. Import the SimpleXMLElement into a DOMElement using dom_import_simplexml().
  2. Use $dom->parentNode->removeChild($dom) to delete the child element from its parent.

Example Code

$data = '<data><seg>

Output

<?xml version="1.0"?>
<data><seg>

XPath Alternative

Alternatively, simplify node selection using XPath, as illustrated in the following code:

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

// Removal procedure as described above

The above is the detailed content of How to Remove a Specific Child Element with a Given Attribute in SimpleXML Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn