php中将SimpleXMLElement Object转化为普通数组
转: http://www.php230.com/transform-simplexmlelement-object-to-array-with-php.html
改成:属性和元素都作为数组的值
php代码:
<?
function xmlToArr($xml, $root = true)
{
if(!$xml->children())
{
return (string)$xml;
}
$array = array();
foreach($xml->children() as $element => $node)
{
$totalElement = count($xml->{$element});
if(!isset($array[$element]))
{
$array[$element] = "";
}
// Has attributes
if($attributes = $node->attributes())
{
$data = array();
foreach($attributes as $attr => $value)
{
$data[$attr] = (string)$value;
}
if($totalElement > 1)
{
$data2 = xmlToArr($node, false);
$array[$element][] = array_merge($data,$data2);
}
else
{
$data2['value'] = (count($node) > 0) ? xmlToArr($node, false) : (string)$node;
$array[$element] = array_merge($data,$data2);
}
}
else
{
if($totalElement > 1)
{
$array[$element][] = xmlToArr($node, false);
}
else
{
$array[$element] = xmlToArr($node, false);
}
}
}
if($root)
{
return array($xml->getName() => $array);
}
else
{
return $array;
}
}
$array = array();
$xml=simplexml_load_file("manhua.xml");
print_r(xmlToArr($xml,false));
manhua.xml
<?xml version="1.0" encoding="utf-8" ?>
<list>
<manhua id="1" abc="2">
<title tt="1">刀剑神域</title>
<test>
<a>1</a>
<b>2</b>
</test>
<test>
<a>11</a>
<b>22</b>
</test>
<dir>djsy</dir>
<img>djsy.jpg</img>
<info></info>
</manhua>
<manhua>
<test>
<a>1</a>
<b>2</b>
</test>
<test>
<a>11</a>
<b>22</b>
</test>
<title>刀剑神域_calibur</title>
<dir>djsy_calibur</dir>
<img>djsy_calibur.jpg</img>
<info></info>
</manhua>
<manhua>
<title>刀剑神域_fairydance</title>
<dir>djsy_fairydance</dir>
<img>djsy_fairydance.jpg</img>
<info></info>
</manhua>
<manhua>
<title>刀剑神域_progressive</title>
<dir>djsy_progressive</dir>
<img>djsy_progressive.jpg</img>
<info></info>
</manhua>
<manhua>
<title>刀剑神域_少女们的乐章</title>
<dir>djsy_snmdyz</dir>
<img>djsy_snmdyz.jpg</img>
<info></info>
</manhua>
<manhua>
<title>刀剑神域_幽灵子弹</title>
<dir>djsy_youlingzidan</dir>
<img>djsy_youlingzidan.jpg</img>
<info></info>
</manhua>
<manhua>
<title>小刀剑神域</title>
<dir>xiaodaojianshenyu</dir>
<img>xiaodaojianshenyu.jpg</img>
<info></info>
</manhua>
<manhua>
<title>新娘summer</title>
<dir>xinian_summer</dir>
<img>xinian_summer.jpg</img>
<info></info>
</manhua>
<manhua>
<title>Sword_ArtOnline_Silica_Edition</title>
<dir>Sword_ArtOnline_Silica_Edition</dir>
<img>Sword_ArtOnline_Silica_Edition.jpg</img>
<info></info>
</manhua>
</list>
Jquery+Ajax,遍历对象和数组:
function listObj(obj,str,level){
if(!obj)
return str;
level++;
for (x in obj)
{
if(typeof(obj[x])=="object"){
str+=x+'---'+level+'级目录--<br/>\n';
str=listObj(obj[x],str,level)
}else{
str+=x+'--'+obj[x]+'<br/>\n';
}
}
return str;
}
$(function(){
$.getJSON("1.php","", function(obj){
var str="";
var manhua=obj.manhua;
$.each(manhua,function(n,value) {
str+='--'+n+'--1级目录---'+'<br/>\n';
str=listObj(value,str,1);
});
$("#st").html(str);
});