将PHP的SimpleXML文档对象转换为标准数组
[coolcode lang=”PHP”]
/**
* SimpleXML对象转换为数组
*
* @param obj $obj SimpleXML 对象
* @return array 经过转换的数组
*/
function simplexml_obj2array($obj){
if ($obj instanceof SimpleXMLElement) {
$obj = (array)$obj;
}
if (is_array($obj)) {
$result = $keys = array();
foreach( $obj as $key=>$value)
{
isset($keys[$key]) ? ($keys[$key] += 1) : ($keys[$key] = 1);
if( $keys[$key] == 1 )
{
$result[$key] = simplexml_obj2array($value);
}
elseif( $keys[$key] == 2 )
{
$result[$key] = array($result[$key], simplexml_obj2array($value));
}
else if( $keys[$key] > 2 )
{
$result[$key][] = simplexml_obj2array($value);
}
}
return $result;
} else {
return $obj;
}
}
[/coolcode]