我有一个xml文件:
<kemo>
<cities>
<area>area1</area >
<city>city1</city>
<status>Lipsum1</status>
</cities>
<cities>
<area>area1</area >
<city>city2</city>
<status>Lipsum2</status>
</cities>
<cities>
<area >area2</area >
<city>city3</city>
<status>Lipsum3</status>
</cities>
<cities>
<area >area2</area >
<city>city4</city>
<status>Lipsum4</status>
</cities>
<cities>
<area >area2</area >
<city>city5</city>
<status>Lipsum5</status>
</cities>
</kemo>
我可以使用simlpeXML通过这个xml,但我不想重复区域名称。我想要一棵这样的树:
area1 city1
city2
area2 city3
city4
city5
与
$request_url = "xml.xml";
$xml = simplexml_load_file($request_url) or die("feed not loading");
foreach($xml->kemo as $value){
echo '<li><span>'.$value->area.' '.$value->city.'</span></li>';
}
我有重复的区域。我怎样才能防止重复孩子?
答案 0 :(得分:5)
这与SimpleXML无关。我的建议是 - 将整个XML加载到数组中然后列出它。如果首先将XML加载到数组中,则可以确保XML列表不会再次出现错误的区域顺序,例如area1,area2,area1。
$xml = simplexml_load_file('xml.xml') or die("feed not loading");
$data = array();
foreach($xml as $value) {
$area = (string)$value->area;
// $area needs to be a string when using as a array key
$data[$area][] = $value->city;
}
然后使用$data
foreach ($data as $area_name => $cities) {
print $area_name;
foreach ($cities as $city) {
print $city;
}
}
答案 1 :(得分:0)
您可以对此进行手动检查:
$xml = simplexml_load_file($request_url) or die("feed not loading");
foreach($xml->kemo as $value){
($value->area == $prev_area) ? $area = "" : $area = $value_area && $prev_area = $area);
echo '<li><span>'.$area.' '.$value->city.'</span></li>';
}
不知道这是否会编译,但你可能会想到:)