note 49040 deleted from ref.simplexml by techtonik

From: Date: Sun, 31 Dec 2006 11:42:48 +0000
Subject: note 49040 deleted from ref.simplexml by techtonik
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-121131@lists.php.net to get a copy of this message
Note Submitter: Daniel FAIVRE - geomaticien.com ---- I've searched a while for a convenient "to array" function, and finally wrote it. These one provide at least 5 cool features: - the MOST IMPORTANT: return a correct structure when several childs nodes have the same name: nodes are numbered properly - read CDATA values - returned array is very easy-to-use - attributes returned in sub-arrays with key [@] - very fast When you create a "xml2array" function, you need to manage nodes with attributes, but without children: i've choosed to ignore their attributes to avoid a "virtual ['value'] node" for such nodes in the returned array. <?php /** * Convert SimpleXMLElement object to array * Copyright Daniel FAIVRE 2005 - www.geomaticien.com * Copyleft GPL license */ function simplexml2array($xml) { if (get_class($xml) == 'SimpleXMLElement') { $attributes = $xml->attributes(); foreach($attributes as $k=>$v) { if ($v) $a[$k] = (string) $v; } $x = $xml; $xml = get_object_vars($xml); } if (is_array($xml)) { if (count($xml) == 0) return (string) $x; // for CDATA foreach($xml as $key=>$value) { $r[$key] = simplexml2array($value); } if (isset($a)) $r['@'] = $a; // Attributes return $r; } return (string) $xml; } ?>

« previous php.notes (#121131) next »