Rumah >pembangunan bahagian belakang >tutorial php >php解析xml到二维数组问题,求大神指导
array(
array("name"=>"haha1",id=1,pid=0),
array("name"=>"haha2",id=2,pid=0),
array("name"=>"haha2,1",id=3,pid=2),
array("name"=>"haha2,2",id=4,pid=2),
array("name"=>"haha3",id=5,pid=0),
array("name"=>"haha3,1",id=6,pid=5),
array("name"=>"haha3.2",id=7,pid=5),
)
?>
把最上面的xml代码转换成下面php数组
下面是我写的代码,转换时候pid不对劲,我怎么调试都不行,还请指导
$xml = simplexml_load_file("hh.xml");
$arr = json_decode(json_encode($xml),TRUE);
print_r(arrto2($arr['hh']));
function arrto2($arr,$pid=0){
static $i=1;
static $data=array();
foreach($arr as $v){
if(is_array($v)){
foreach($v as $z => $x){
if($z==="@attributes"){
$v["@attributes"]['id']=$i;
$v["@attributes"]['pid']=$pid;
$data[$i]=$v["@attributes"];
}else{
arrto2($x,$i);
}
$i++;
}
}
}
return $data;
}
现在问题解决了,不错还有一个问题,解析中文时候会乱码,编码是gb2312,用utf8正常
问题解决了
arrto2($x,$v["@attributes"]['id']);就ok了
加上meta charset就不会乱码了。
hh.xml
<?xml version="1.0" encoding="gb2312"?><www><hh name="haha1哈哈" /><hh name="haha2哈哈"><hh name="haha2.1哈哈" /><hh name="haha2.2哈哈" /></hh><hh name="haha3哈哈"><hh name="haha3.1哈哈" /><hh name="haha3.2哈哈" /></hh></www>
<?php$xml = simplexml_load_file("hh.xml");$arr = json_decode(json_encode($xml),TRUE);echo '<meta http-equiv="content-type" content="text/html;charset=utf-8">';print_r(arrto2($arr['hh']));function arrto2($arr,$pid=0){ static $i=1; static $data=array(); foreach($arr as $v){ if(is_array($v)){ foreach($v as $z => $x){ if($z==="@attributes"){ $v["@attributes"]['id']=$i; $v["@attributes"]['pid']=$pid; $data[$i]=$v["@attributes"]; }else{ arrto2($x,$i); } $i++; } } } return $data;}?>
Array( [1] => Array ( [name] => haha1哈哈 [id] => 1 [pid] => 0 ) [2] => Array ( [name] => haha2哈哈 [id] => 2 [pid] => 0 ) [3] => Array ( [name] => haha2.1哈哈 [id] => 3 [pid] => 3 ) [4] => Array ( [name] => haha2.2哈哈 [id] => 4 [pid] => 3 ) [6] => Array ( [name] => haha3哈哈 [id] => 6 [pid] => 0 ) [7] => Array ( [name] => haha3.1哈哈 [id] => 7 [pid] => 7 ) [8] => Array ( [name] => haha3.2哈哈 [id] => 8 [pid] => 7 ))