Search code examples
phparrayssimplexml

XML Data to multidimensional Array


I've got the following problem: After adding data to an array, it only stores the last insert.

I get the following result from my Code with var_dump:

array(5) { ["Mount01"]=> string(12) "DebugLevel#0" ["Mount02"]=> string(12) "DebugLevel#0" ["Mount03"]=> string(12) "DebugLevel#0" ["Mount04"]=> string(12) "DebugLevel#0" ["Mount05"]=> string(12) "DebugLevel#0" } 

So it only saves the last input that I do. But I want it like that:

array(X) { ["Mount01"]=> string(XX) "DebugLevel#0" ["Mount01"]=> string(XX) "Bla#5" ["Mount02"]=> string(XX) "DebugLevel#0" ["Mount02"]=> string(XX) "Bla#5" }

This is my XML Structure:

<Config>
  <Core>
    <Store>
      <Mount01>
                <DebugLevel>0</DebugLevel>
                <Bla>5</Bla>
      <Mount02>
                <DebugLevel>0</DebugLevel>
                <Bla>5</Bla>

This is my Code:

class Storage{
  public static function get_storage_data()
  {
    if(file_exists('/var/www/content/data/data.xml')) :
        $xml = simplexml_load_file('/var/www/content/data/data.xml');
        foreach ($xml->Core->Store as $mounts) {
          foreach ($mounts as $mount) {
            foreach ($mount->Children() as $value) {
              $store[$mount->getName()]=$value->getName()."#".$value;
            }
          }
        }
        var_dump($store);
    else:
        write_log(sprintf("data.xml not found"));
    endif;
  }

So, how can I achive my wanted Output? Also Code improvements are welcome.


Solution

  • public static function get_storage_data(
    {
        if(file_exists('/var/www/content/data/data.xml')) :
            $xml = simplexml_load_file('/var/www/content/data/data.xml');
            foreach ($xml->Core->Store as $mounts) {
              foreach ($mounts as $mount) {
                $data=[];
                foreach ($mount->Children() as $value) {
                  array_push($data,[$value->getName()."#".$value]);
                }
                $store[$mount->getName()]=$data;
              }
            }
        else:
            write_log(sprintf("data.xml not found"));
        endif;
      }
    

    Answer to my Problem.