note 128000 added to simplexmlelement.addchild

From: Date: Fri, 09 Dec 2022 11:31:28 +0000
Subject: note 128000 added to simplexmlelement.addchild
Groups: php.notes 
Request: Send a blank email to php-notes+get-219956@lists.php.net to get a copy of this message
Just in case anyone else, like me, was trying to figure out a way to remove child elements... <?php $xml = <<<EOF <?xml version="1.0" encoding="utf-8" ?> <Animals> <Dog breed="chihuahua"/> <Dog breed="poodle"/> <Dog breed="invalid"/> </Animals> EOF; $animals = new SimpleXMLElement($xml); unset($animals->Dog[2]); echo $animals->asXML(); // <?xml version="1.0" encoding="utf-8"?> // <Animals> // <Dog breed="chihuahua"/> // <Dog breed="poodle"/> // // </Animals> ?> Note: you cannot remove elements while iterating children, otherwise it will break the Iterator. Example: <?php $xml = <<<EOF <?xml version="1.0" encoding="utf-8" ?> <Animals> <Dog breed="chihuahua"/> <Dog breed="poodle"/> <Dog breed="invalid"/> </Animals> EOF; $animals = new SimpleXMLElement($xml); $allowed_breeds = [ 'chihuahua', 'poodle' ]; try { $index = 0; foreach ($animals->Dog as $dog) { if (!in_array($dog['breed'], $allowed_breeds)) { unset($animals->Dog[$index]); } $index++; } } catch (Throwable $e) { echo $e->getMessage(); // SimpleXMLElement is not properly initialized } ?> ---- Server IP: 45.112.84.4 Probable Submitter: 185.85.3.175 (proxied: 144.129.235.105) ---- Manual Page -- https://php.net/manual/en/simplexmlelement.addchild.php Edit -- https://main.php.net/note/edit/128000 Del: integrated -- https://main.php.net/note/delete/128000/integrated Del: useless -- https://main.php.net/note/delete/128000/useless Del: bad code -- https://main.php.net/note/delete/128000/bad+code Del: spam -- https://main.php.net/note/delete/128000/spam Del: non-english -- https://main.php.net/note/delete/128000/non-english Del: in docs -- https://main.php.net/note/delete/128000/in+docs Del: other reasons-- https://main.php.net/note/delete/128000 Reject -- https://main.php.net/note/reject/128000 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#219956) next »