note 117406 added to simplexml.examples-basic
| From: | rowan dot collins at gmail dot com | Date: | Thu, 04 Jun 2015 18:58:59 +0000 |
| Subject: | note 117406 added to simplexml.examples-basic | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-202748@lists.php.net to get a copy of this message | ||
There is a common "trick" often proposed to convert a SimpleXML object to an array, by
running it through json_encode() and then json_decode(). I'd like to explain why this is a bad
idea.
Most simply, because the whole point of SimpleXML is to be easier to use and more powerful than a
plain array. For instance, you can write <?php $foo->bar->baz['bing'] ?> and
it means the same thing as <?php $foo->bar[0]->baz[0]['bing'] ?>, regardless
of how many bar or baz elements there are in the XML; and if you write <?php
(string)$foo->bar[0]->baz[0] ?> you get all the string content of that node - including
CDATA sections - regardless of whether it also has child elements or attributes. You also have
access to namespace information, the ability to make simple edits to the XML, and even the ability
to "import" into a DOM object, for much more powerful manipulation. All of this is lost by
turning the object into an array rather than reading understanding the examples on this page.
Additionally, because it is not designed for this purpose, the conversion to JSON and back will
actually lose information in some situations. For instance, any elements or attributes in a
namespace will simply be discarded, and any text content will be discarded if an element also has
children or attributes. Sometimes, this won't matter, but if you get in the habit of converting
everything to arrays, it's going to sting you eventually.
Of course, you could write a smarter conversion, which didn't have these limitations, but at
that point, you are getting no value out of SimpleXML at all, and should just use the lower level
XML Parser functions, or the XMLReader class, to create your structure. You still won't have
the extra convenience functionality of SimpleXML, but that's your loss.
----
Server IP: 72.52.91.14
Probable Submitter: 62.189.198.114
----
Manual Page -- http://php.net/manual/en/simplexml.examples-basic.php
Edit -- https://master.php.net/note/edit/117406
Del: integrated -- https://master.php.net/note/delete/117406/integrated
Del: useless -- https://master.php.net/note/delete/117406/useless
Del: bad code -- https://master.php.net/note/delete/117406/bad+code
Del: spam -- https://master.php.net/note/delete/117406/spam
Del: non-english -- https://master.php.net/note/delete/117406/non-english
Del: in docs -- https://master.php.net/note/delete/117406/in+docs
Del: other reasons-- https://master.php.net/note/delete/117406
Reject -- https://master.php.net/note/reject/117406
Search -- https://master.php.net/manage/user-notes.php