note 94062 deleted from book.simplexml by googleguy

From: Date: Tue, 22 Oct 2013 11:17:42 +0000
Subject: note 94062 deleted from book.simplexml by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-197084@lists.php.net to get a copy of this message
Note Submitter: spcmky at gmail dot com ---- 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.

« previous php.notes (#197084) next »