function xml2array($xml_obj) {
$sxi = new SimpleXmlIterator($xml_obj); // read from xml string
//$sxi = new SimpleXmlIterator($xml_obj, null, true); // read from filename
return sxiToArray($sxi);
}

function sxiToArray($sxi) {
$a = array();
for( $sxi->rewind(); $sxi->valid(); $sxi->next() ) {
if(!array_key_exists($sxi->key(), $a)) {
$a[$sxi->key()] = array();
} else if(!isset($a[$sxi->key()][0])) {
$exists_value = $a[$sxi->key()];
$a[$sxi->key()] = array();
$a[$sxi->key()][] = $exists_value;
}

if($sxi->hasChildren()) {
if(isset($a[$sxi->key()][0])) {
$a[$sxi->key()][] = sxiToArray($sxi->current());
} else {
$a[$sxi->key()] = sxiToArray($sxi->current());
}
} else {
if(isset($a[$sxi->key()][0])) {
$a[$sxi->key()][] = strval($sxi->current());
} else {
$a[$sxi->key()] = strval($sxi->current());
}
}
}
return $a;
}

사용상 편의를 위해 약간 수정했음

by 뭔일이여 2010. 7. 22. 10:37
| 1 |