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
Release: 2024-12-15 13:46:20
Original
275 people have browsed it

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>
Copy after login

Output

<?xml version="1.0"?>
<data><seg>
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template