xml如下:
http://www.hu-rong.com
www.hu-rong.com
转为数据结构如下:Array
(
[item] => Array
(
[0] => Array
(
[@attributes] => Array
(
[index] => 0
)
[name] => Array
(
[@attributes] => Array
(
[a] => a0
[b] => b0
)
)
[site] => http://www.hu-rong.com
)
[1] => Array
(
[@attributes] => Array
(
[index] => 1
)
[name] => Array
(
[@attributes] => Array
(
[a] => a1
[b] => b1
)
)
[site] => www.hu-rong.com
)
)
)
奇怪的是site的属性丢了
php读xml
$xml=simplexml_load_file('test.xml');
//print_r(json_decode(json_encode($xml),true));
echo $xml->getName().'节点下有'.$xml->count().'个item
';
foreach($xml as $item){
$str='';
$child=$item->children();
$attributes=$child->attributes();
$str.='index为'.$item->attributes()->index.'item下有';
$str.=$child[0]->getName().'(属性'.$attributes[0]->getName().'=>'.$attributes[0].','.$attributes[1]->getName().'=>'.$attributes[1].')和';
$str.=$child[1]->getName().'节点';
$str.='其值分别为:'.$item->name.','.$child[1].'
';
echo $str;
}
结果如下:
index为0item下有name(属性a=>a0,b=>b0)和site节点其值分别为:张三,http://www.hu-rong.com
index为1item下有name(属性a=>a1,b=>b1)和site节点其值分别为:李四,www.hu-rong.com
list节点下有2个item
例2:
$xml=simplexml_load_file('test.xml');
//print_r(json_decode(json_encode($xml),true));
$count=$xml->count();
echo $xml->getName().'节点下有'.$count.'个item
';
$i=0;
foreach($xml as $item){
$str='';
$child=$item->children()[$i];
$attributes=$child->attributes();
$str.='index为'.$item->attributes()->index.'的item下的';
$str.=$child->getName().'(属性'.$attributes->getName().'=>'.$attributes[0].','.$attributes[1]->getName().'=>'.$attributes[1].')';
$str.='其值分别为:'.$child.'
';
echo $str;
$i++;
}
运行结果:
index为0的item下的name(属性a=>a0,b=>b0)其值分别为:张三
index为1的item下的site(属性c=>c1,d=>d1)其值分别为:www.hu-rong.com
list节点下有2个item