php read nested sections in ini file

19 Views Asked by At

I try to read the file names.ini below into a php array and then access certain repeating sections within the code.

My code does not work correct, the base problem seems to be, that ini files don't have a structure to nest sections.

But: could there be a workaround if the code would be slightly modified???

File names.ini:

[baseSetup]

  sections[] = name
  sections[] = place

[name][1]
  DummyName1
[name][2]
  DummyName2
[name][3]
  DummyName3

[place][]
New York
[place][]
Texas
[place][]
San Francisco

Php-script to read the file:

<?php
   $setup =  parse_ini_file("names.ini",true);
   print_r($setup);
   echo("<br/> ---------------<br/>");
   
   echo ("setup[name = " . $setup["name"] . "<br/>");
   print_r($setup["name"]);
   echo ("<br/><br/>");

   foreach ($setup["baseSetup"] as $key => $val) {
     echo ("key: $key:<br/>");
     print_r($val);
     
     foreach($val as $idx) {
     
       echo ("<br/>count of $idx: " . count($setup[$idx]) . "<br/>");
     
     }     
     echo ("<br/>");
     
   }
    
?>

Further specification:

I could write it this way:

[baseSetup]
  nSections = 2
  
[sections] 
  name = 3
  place = 4
  
[name1] 
content = DummyName1
 
[name2]  
content = DummyName2

[name3]  
content = DummyName3      

[place1]  
content = New York
[place2]  
content = Texas
[place3]  
content= San Francisco
[place4]  
content= Boston

And read it like this:

 <?php
   $setup =  parse_ini_file("names2.ini",true);
   
   print_r($setup);
   echo("<br/> ---------------<br/>");
   
   $nNames = $setup["sections"]["name"];
   $nPlaces = $setup["sections"]["place"];
   
   for ($i=1;$i<=$nNames;$i++) {
     $key = "name".$i;
     echo ("name = "); print_r($setup[$key]); echo("<br/>");
   }

   for ($i=1;$i<=$nPlaces;$i++) {
     $key = "place".$i;       
     echo ("place = "); print_r($setup[$key]); echo("<br/>");
   }
    

?>

So this would work as a basis. But it would like to access the names and places without having to explicitly name their number in the ini file.

0

There are 0 best solutions below