note 127997 added to simplexmlelement.addattribute
| From: | caffeinatedbits at main dot php dot net | Date: | Fri, 09 Dec 2022 10:26:46 +0000 |
| Subject: | note 127997 added to simplexmlelement.addattribute | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-219953@lists.php.net to get a copy of this message | ||
I needed a way to update an attribute, but I could not find any documented way to do this.
After much experimentation, here's my findings of what works - the answer was so simple it took
me 8 tries to figure it out :-)
Given the following example:
<?php
$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
<Dog/>
</Animals>
EOF;
$animals = new SimpleXMLElement($xml);
echo $animals->Dog->asXML();
// <Dog/>
?>
Test #6 - maybe directly modifying the attributes() Iterator like an array will secretly call
__set() magic method?
TL;DR: yep
<?php
...
$animals->Dog->addAttribute('breed', "chihuahua");
echo $animals->Dog->asXML();
// <Dog breed="chihuahua">
$dogAttrs = $animals->Dog->attributes();
// object(SimpleXMLElement)#4 (1) {
// ["@attributes"]=>
// array(1) {
// ["breed"]=>
// string(9) "chihuahua"
// }
// }
$dogAttrs['breed'] = "poodle";
// works!
echo $animals->Dog->asXML();
// <Dog breed="poodle">
?>
Test #7 - maybe I don't even need to call attributes() at all?
TL;DR: I sure don't!
<?php
...
$animals->Dog->addAttribute('breed', "chihuahua");
echo $animals->Dog->asXML();
// <Dog breed="chihuahua">
$animals->Dog['breed'] = "poodle";
// works!
echo $animals->Dog->asXML();
// <Dog breed="poodle">
?>
Test #8 - Maybe I never needed to call addAttribute() in the first place?
TL;DR: nope, I can skip that altogether!
<?php
...
$animals->Dog['breed'] = "chihuahua";
// works!
echo $animals->Dog->asXML();
// <Dog breed="chihuahua">
$animals->Dog['breed'] = "poodle";
// works!
echo $animals->Dog->asXML();
// <Dog breed="poodle">
?>
FYI: I also submitted another separate note with what does NOT work just in case you, like me, are
curious and tempted to try another way.
----
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.addattribute.php
Edit -- https://main.php.net/note/edit/127997
Del: integrated -- https://main.php.net/note/delete/127997/integrated
Del: useless -- https://main.php.net/note/delete/127997/useless
Del: bad code -- https://main.php.net/note/delete/127997/bad+code
Del: spam -- https://main.php.net/note/delete/127997/spam
Del: non-english -- https://main.php.net/note/delete/127997/non-english
Del: in docs -- https://main.php.net/note/delete/127997/in+docs
Del: other reasons-- https://main.php.net/note/delete/127997
Reject -- https://main.php.net/note/reject/127997
Search -- https://main.php.net/manage/user-notes.php