php解析xml到二維數組問題,求大神指導

來源:互聯網
上載者:User
















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

 


';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        ))
  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.