PHP中 xml转数组

来源:互联网 发布:maclc如何安装windows 编辑:程序博客网 时间:2024/03/29 19:30
<?php$simxml = simplexml_load_file('./book.xml');//print_r($sim);//把XML塞进数组中$arr = array();function xml2arr($sim){//如果是对象,则强转$arr = (array)$sim;//读强转后的数组做foreach循环foreach ($arr as $k => $v) {if ($v instanceof simplexmlElement ||  is_array ($v)) {$arr[$k] = xml2arr($v);}}return $arr;}print_r($xmlarr = xml2arr($simxml)) ;echo $xmlarr['book']['1']['@attributes']['category'];?>



一下是运行结果:

Array ( [book] => Array ( [0] => Array ( [@attributes] => Array ( [category] => COOKING ) [title] => Everyday Italian [author] => Giada De Laurentiis [year] => 2005 [price] => 30.00 ) [1] => Array ( [@attributes] => Array ( [category] => 武侠 ) [title] => 侠客行 [author] => 金庸 [year] => 2005 [price] => 29.99 ) [2] => Array ( [@attributes] => Array ( [category] => 网页 ) [title] => Jquery 7日通 [author] => 小二虎 [year] => 2003 [price] => 49.99 ) [3] => Array ( [@attributes] => Array ( [category] => 网页 ) [title] => Learning XML [author] => Erik T. Ray [year] => 2003 [price] => 39.95 [edition] => 第三版 ) ) ) 武侠

使用到的XML文件如下:

<?xml version ='1.0' encoding='utf8'?><bookstore><book category='COOKING'><title lang='en'>Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book><book category='武侠'><title lang='中文'>侠客行</title><author>金庸</author><year>2005</year><price>29.99</price></book><book category='网页'><title lang='中文'>Jquery 7日通</title><author>小二虎</author><year>2003</year><price>49.99</price></book><book category='网页'><title lang='en'>Learning XML</title><author>Erik T. Ray</author><year>2003</year><price>39.95</price><edition>第三版</edition></book></bookstore>


0 0
原创粉丝点击