tags:

views:

44

answers:

2

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? Thanks in advanced

+5  A: 

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;
    }
}
dwich
This was a very elegant solution :-)
Burbas
Warning: Illegal offset type in
phpExe
@dwich: +1 I didn't get his question fully probably.
Sarfraz
@phpExe: Fixed. $value->area has to be converted to string if you want to use it as an array key.
dwich
Yes, there is syntax error. Is it hard to find for you? Sorry for being sarcastic. It should be `foreach ($data as $area_name => $cities)`
dwich
"Is it hard to find for you?" , No, Its not hard, Im sorry.:(million thanks...
phpExe
A: 

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 :)

Burbas