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;
}

 

  • Great Answer 1
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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.