将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]

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据