3
我有一個XML文件,我想將其顯示爲多級列表XML「樹」,以多層次的HTML列表
<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>
標籤
對我的方法有任何建議嗎?有沒有其他方法可以做到這一點?
另一種可能性是使用XSLT。見[這個類似的問題](http://stackoverflow.com/questions/6282357/xslt-transformation-search-nodes-and-return-hierarchical-parents)。 – JRL