note 49040 added to ref.simplexml
| From: | DanielFAIVRE-geomaticien dot com at osu1 dot php dot net | Date: | Fri, 14 Jan 2005 23:46:47 +0000 |
| Subject: | note 49040 added to ref.simplexml | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-83290@lists.php.net to get a copy of this message | ||
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;
}
?>
----
Manual Page -- http://www.php.net/manual/en/ref.simplexml.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+49040
Delete -- http://master.php.net/manage/user-notes.php?action=delete+49040&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+49040&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+49040&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+49040&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+49040&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+49040&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+49040&report=yes
Search -- http://master.php.net/manage/user-notes.php