Php parses xml to a two-dimensional array. please instruct me to edit this post by community147 at 2014-08-2821: 10: 54 at last & lt ;? Xml & nbsp; version1.0 & nbsp; encodinggb2312? & Gt; & lt; www & gt; & lt; hh & nbsp; nameha php parses xml to a two-dimensional array.
This post was last edited by community147 at 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 ),
)
?>
Convert the top xml code to the following php array
The following is the code I wrote. The pid is incorrect during the conversion, and I cannot debug it. please also guide
$ 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;
}
Now the problem has been solved. there is another problem. garbled characters are generated when parsing Chinese characters. the encoding is gb2312, and utf8 is normal.
------ Solution --------------------
The meta charset will not be garbled.
Hh. xml
$xml = simplexml_load_file("hh.xml");
$arr = json_decode(json_encode($xml),TRUE);
echo '
';
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 haha
[Id] => 1
[Pid] => 0