confusing about simpleXML
I have a xml file:
<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>
I can walk trough this xml with simlpeXML, but I dont want to repeat area names. I want a tree like this:
area1 city1
city2
area2 city3
city4
city5
with
开发者_开发问答$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>';
}
I have repeated area. How can I prevent repeating child?
This is not about SimpleXML. What I suggest is - load the whole XML into array and then list it. If you load the XML into array first, you can be sure that the listing of XML won't be corrupted with wrong area order like area1, area2, area1 again.
$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;
}
Then work with $data
foreach ($data as $area_name => $cities) {
print $area_name;
foreach ($cities as $city) {
print $city;
}
}
You can do a manual check for this:
$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>';
}
Don't know if this will compile, but you might get the idea :)
精彩评论