Home >Backend Development >PHP Tutorial >php解析xml到二维数组有关问题,求大神指导

php解析xml到二维数组有关问题,求大神指导

WBOY
WBOYOriginal
2016-06-13 12:06:101075browse

php解析xml到二维数组问题,求大神指导

本帖最后由 community147 于 2014-08-28 21:10:54 编辑















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正常

------解决方案--------------------
加上meta charset就不会乱码了。

hh.xml
<br /><?xml version="1.0" encoding="gb2312"?><br /><www><br /><hh name="haha1哈哈" /><br /><hh name="haha2哈哈"><br /><hh name="haha2.1哈哈" /><br /><hh name="haha2.2哈哈" /></hh><br /><hh name="haha3哈哈"><br /><hh name="haha3.1哈哈" /><br /><hh name="haha3.2哈哈" /><br /></hh><br /></www><br />


<br /><?php<br />$xml = simplexml_load_file("hh.xml");<br />$arr = json_decode(json_encode($xml),TRUE);<br />echo '<meta http-equiv="content-type" content="text/html;charset=utf-8">';<br />print_r(arrto2($arr['hh']));<br />function arrto2($arr,$pid=0){<br />    static $i=1;<br />    static $data=array();<br />    foreach($arr as $v){<br />        if(is_array($v)){<br />            foreach($v as $z => $x){<br />                if($z==="@attributes"){<br />                    $v["@attributes"]['id']=$i;<br />                    $v["@attributes"]['pid']=$pid;<br />                $data[$i]=$v["@attributes"];<br /><br />                }else{<br />                    arrto2($x,$i);<br />                }<br />                <br />                $i++;<br />            }<br />        }<br />    }<br />    return $data;<br />}<br />?><br />


<br>Array<br>(<br>    [1] => Array<br>        (<br>            [name] => haha1哈哈<br>            [id] => 1<br>            [pid] => 0<div class="clear">
                 
              
              
        
            </div>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn