Artan Telkiu
Artan Telkiu

Reputation: 33

Processing xml file

I have the following xml file:


    row category="1" category_name="CatA" entry_id="1" entry_name="A1" 
    row category="1" category_name="CatA" entry_id="2" entry_name="A2" 
    row category="1" category_name="CatA" entry_id="3" entry_name="A3" 
    row category="2" category_name="CatB" entry_id="4" entry_name="B1" 
    row category="2" category_name="CatB" entry_id="5" entry_name="B2" 
    row category="2" category_name="CatB" entry_id="6" entry_name="B3" 
    row category="3" category_name="CatC" entry_id="7" entry_name="C1" 
    row category="4" category_name="CatD" entry_id="8" entry_name="D1"

and I want to produce below html:

CatA
----A1
----A2
----A3
CatB
----B1
----B2
----B3
CatC
----C1
CatD
----D1

for this I am using below php xml parser:

 

$ndeshjet=simplexml_load_file("xml_file.xml");

$new_category = 1;

foreach ($ndeshjet->row as $entry) {

      $category = $entry['category'];
        if ($category  <> $new_category){
             $category_name = $entry['category_name'];
             echo $category_name."</br>";   
             $new_category = $category;
        } else {
             $entry_name  = $entry['entry_name'];
             echo "----".$entry_name."</br>";       
        }
}

?>

but the result is :

----A1 ----A2 ----A3 CatB CatB CatB CatC CatD

Thanks in advance

Upvotes: 1

Views: 44

Answers (1)

Kevin
Kevin

Reputation: 41885

As an alternative, you could gather all the values first inside an array and make the category name as key pushing same keys inside. After thats done and gathered, print them accordingly:

$categories = array();
// gather inside container
foreach ($ndeshjet->row as $entry) {
    $category_name = (string) $entry->attributes()->category_name;
    $entry_name = (string) $entry->attributes()->entry_name;
    $categories[$category_name][] = $entry_name;
}

// presentation
foreach($categories as $category_name => $entries) {
    echo $category_name . '<br/>';
    foreach($entries as $entry) {
        echo '----' . $entry . '<br/>';
    }
}

Sample Output

Upvotes: 1

Related Questions