我有一个 XML 文件,我想将其显示为多级列表
<items>
<item>
<parent_id>1</parent_id>
<id>1876</id>
<name>foobar1</name>
</item>
<item>
<parent_id>1876</parent_id>
<id>1877</id>
<name>foobar11</name>
</item>
<item>
<parent_id>1877</parent_id>
<id>1878</id>
<name>foobar111</name>
</item>
<item>
<parent_id>1877</parent_id>
<id>1879</id>
<name>foobar112</name>
</item>
<item>
<parent_id>1877</parent_id>
<id>1880</id>
<name>foobar113</name>
</item>
...
</items>
我想显示如下:
<ul>
<li>foobar1</li>
<li>
<ul>
<li>foobar11</li>
<li>
<ul>
<li>foobar111</li>
<li>foobar112</li>
<li>foobar113</li>
</ul>
</li>
</ul>
</li>
...
</ul>
我尝试循环执行(我使用的是 simplexml):
$catxml = simplexml_load_file('file.xml');
$nodes=$catxml->xpath("//item");
$gile=0;
$ile=0;
foreach($nodes as $node) {
$par = $node->parent_id;
$id = $node->id;
$naz = $node->name;
if($par=='1'){ $gile++; $ile++; echo '<li><a href="#url">'.$id.'-'.$naz.'</a></li>';
settype($id,'integer');
foreach($nodes as $nodea) {
$apar = $nodea->parent_id;
$aid = $nodea->id;
$anaz = $nodea->name;
settype($aid,'integer');
$apoczatek='';
if($apar!='1' AND $apar==$id AND $aid>$id){ $ile++; if($apoczatek!=''){echo '</ul></li>';}echo '<li><ul><li><a href="#url">'.$aid.'-'.$anaz.'</a></li>';
foreach($nodes as $nodea) {
$bpar = $nodea->parent_id;
$bid = $nodea->id;
$bnaz = $nodea->name;
$bpoczatek='';
settype($bid,'integer');
if($bpar==$aid AND $bid>$aid){ $ile++; if($bpoczatek!=''){echo '</ul>';}echo '<ul><li><a href="#url">'.$bid.'-'.$bnaz.'</a></li>';
foreach($nodes as $nodea) {
$cpar = $nodea->parent_id;
$cid = $nodea->id;
$cnaz = $nodea->name;
$cpoczatek='';
settype($cid,'integer');
if($cpar==$bid AND $cid>$bid){ $ile++; if($cpoczatek!=''){echo '</ul>';}echo '<ul><li><a href="#url">'.$cid.'-'.$cnaz.'</a></li>';
foreach($nodes as $nodea) {
$dpar = $nodea->parent_id;
$did = $nodea->id;
$dnaz = $nodea->name;
$dpoczatek='';
settype($did,'integer');
if($dpar==$cid AND $did>$cid){ $ile++; if($dpoczatek!=''){echo '</ul>';}echo '<ul><li><a href="#url">'.$did.'-'.$dnaz.'</a></li>';
foreach($nodes as $nodea) {
$epar = $nodea->parent_id;
$eid = $nodea->id;
$enaz = $nodea->name;
$epoczatek='';
settype($eid,'integer');
if($epar==$did AND $eid>$did){ $ile++; if($epoczatek!=''){echo '</ul>';}echo '<ul><li><a href="#url">'.$eid.'-'.$enaz.'</a></li>';
}
}
}
}
}
}
}
}
}
}
}
}
但它没有用 - 错过<ul>
和</ul>
标签
对我的方法有什么建议吗?还有其他方法吗?