note 44271 modified in ref.simplexml by aidan
| From: | aidan@php.net | Date: | Wed, 22 Dec 2004 07:24:27 +0000 |
| Subject: | note 44271 modified in ref.simplexml by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-82155@lists.php.net to get a copy of this message | ||
the simplexml_to_array function below has a bug, if there are 2 or more fields, it get's bit
out of control, here is the right one:
<?
function simplexml_to_array($xml) {
$ar = array();
foreach($xml->children() as $k => $v) {
// recurse the child
$child = simplexml_to_array($v);
// if it's not an array, then it was empty, thus a value/string
if( count($child) == 0 ) {
$child = (string)$v;
}
// add the childs attributes as if they where children
foreach( $v->attributes() as $ak => $av ) {
// if the child is not an array, transform it into one
if( !is_array( $child ) ) {
$child = array( "value" => $child );
}
$child[$ak] = (string)$av;
}
// if the $k is already in our children list, we need to transform
// it into an array, else we add it as a value
if (!in_array($k,array_keys($ar))) {
$ar[$k] = $child;
} elseif (@in_array(0,@array_keys($ar[$k]))) {
$ar[$k][] = $child;
} else {
$ar[$k] = array($ar[$k]);
$ar[$k][] = $child;
}
}
return $ar;
}
?>
--was--
the simplexml_to_array function below has a bug, if there are 2 or more fields, it get's bit
out of control, here is the right one:
<?
function simplexml_to_array($xml) {
$ar = array();
foreach($xml->children() as $k => $v) {
// recurse the child
$child = simplexml_to_array($v);
// if it's not an array, then it was empty, thus a value/string
if( count($child) == 0 ) {
$child = (string)$v;
}
// add the childs attributes as if they where children
foreach( $v->attributes() as $ak => $av ) {
// if the child is not an array, transform it into one
if( !is_array( $child ) ) {
$child = array( "value" => $child );
}
$child[$ak] = (string)$av;
}
// if the $k is already in our children list, we need to transform
// it into an array, else we add it as a value
if (!in_array($k,array_keys($ar))) {
$ar[$k] = $child;
} elseif (is_array($ar[$k][0])) {
$ar[$k][] = $child;
} else {
$ar[$k] = array($ar[$k]);
$ar[$k][] = $child;
}
}
return $ar;
}
?>
http://php.net/manual/en/ref.simplexml.php