note 94062 added to book.simplexml
| From: | spcmky at gmail dot com | Date: | Wed, 14 Oct 2009 17:49:26 +0000 |
| Subject: | note 94062 added to book.simplexml | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-161730@lists.php.net to get a copy of this message | ||
There are issues with most examples of converting a simplexml object into an array recursively. The
situation that fails is when you have a value for an element and attributes. For example:
<results found="yes">
<warehouse>
<name>WH3</name>
<phone>2-1121</phone>
</warehouse>
<items count="3">
<item id="E1120" bin="AA21">Desk</item>
<item id="E1121" bin="FG03">Chair</item>
<item id="E1122" bin="CD00">Table</item>
</items>
</results>
If you :
<?php
$obj = simplexml_load_string($xml);
print_r($obj);
?>
You will get:
(
[@attributes] => Array
(
[found] => yes
)
[warehouse] => SimpleXMLElement Object
(
[name] => WH3
[phone] => 2-1121
)
[items] => SimpleXMLElement Object
(
[@attributes] => Array
(
[count] => 3
)
[item] => Array
(
[0] => Desk
[1] => Chair
[2] => Table
)
)
)
Where is the rest of the data for the items? If you were to traverse recursively through the object
the item information is in fact there. The problem is how to represent an element as an array that
has a value and attributes. Most of the solution's just ignore the attributes.
print_r, var_dump, and get_object_vars ignore the attributes in this special case from what
I've found.
Here is a simple function to convert the object into an array but it still fails to deal with the
attributes.
<?php
function ToArray ( $data )
{
if (is_object($data)) $data = get_object_vars($data);
return (is_array($data)) ? array_map(__FUNCTION__,$data) : $data;
}
?>
So why even bother trying to convert the object to an array? Simply because of serialization for
caching the object.
One solution would be to create an index called "value" and assign that the element's
value. This way the attributes could coexist.
----
Server IP: 69.147.83.197
Probable Submitter: 69.157.131.99
----
Manual Page -- http://www.php.net/manual/en/book.simplexml.php
Edit -- https://master.php.net/note/edit/94062
Del: integrated -- https://master.php.net/note/delete/94062/integrated
Del: useless -- https://master.php.net/note/delete/94062/useless
Del: bad code -- https://master.php.net/note/delete/94062/bad+code
Del: spam -- https://master.php.net/note/delete/94062/spam
Del: non-english -- https://master.php.net/note/delete/94062/non-english
Del: in docs -- https://master.php.net/note/delete/94062/in+docs
Del: other reasons-- https://master.php.net/note/delete/94062
Reject -- https://master.php.net/note/reject/94062
Search -- https://master.php.net/manage/user-notes.php