Jump to content

Parse XML file to multidimensional array


exxer

Recommended Posts

Hello,

Im trying to figure out how to create multidimensional array from xml file that looks like this:

<root>
  <item>
    <name>name A</name>
    <category>category 1</name>
    <desc>desc A</desc>
  </item>
  <item>
    <name>name B</name>
    <category>category 1</name>
    <desc>desc B</desc>
  </item>
  <item>
    <name>name C</name>
    <category>category 2</name>
    <desc>desc C</desc>
  </item>
</root>

In the end i would like to get output that have items grouped under their categories, something like this:

Category 1

    name A

    desc A

    name B

    desc B

Category 2

    name C

    desc C

 

I have a clue on how to pull the data out of array but I cant figure out how to actually make it :)

Any help or directions would be great, thanks!

 

Link to comment
Share on other sites

If you want this

Array
(
    [category 1] => Array
        (
            [name A] => desc A
            [name B] => desc B
        )

    [category 2] => Array
        (
            [name C] => desc C
        )

)

Then

$xml = simplexml_load_string($input);
$cats = [];
foreach ($xml->item as $itm) {
    if (!isset($cats[(string)$itm->category])) {
        $cats[(string)$itm->category] = [];
    }
    $cats[(string)$itm->category][(string)$itm->name] = (string)$itm->desc;
}

 

Link to comment
Share on other sites

So many thanks Barand, that is what I need.

Your code combined with this

foreach($cats as $cat=>$data){
     echo "$cat <br />";
     foreach($data as $name=>$desc){
          echo "$name<br />  ($desc)<br />";
     }
}

gave me output that I wanted.

Again, many thanks.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.