Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Parsing an INI File

Coding

Parsing an INI File

by  skiflyer  Posted    (Edited  )
I find the PHP included parse_ini_file() function to be junk, with required quoting, and inability to use special characters. So I wrote me own. It's still only a read function... but for many many applications I find that to be enough, and by putting it all into memory it's faster than hitting the file everytime I want a value.

Code:
function parseIniFile($data_file) {
  //Since the PHP version sucks
  $on = false;  //Represents writing the section information should be turned on
  $rows = file($data_file);
  $ini_parsed = array();
  foreach ($rows as $row) {
    $row = trim($row);
    //Conditional skips comments  (middle of line comments not supported)
    if (substr($row, 0, 1) != "#") {
      $pattern = "/\[([a-zA-Z0-9_ ]*)\]/";
      $replacement = "\$1";
      foreach($rows as $row) {
	if (preg_match($pattern, $row)) {
	  $section_name = preg_replace($pattern, $replacement, $row);
	  $section_name = trim($section_name);
	  $ini_parsed[$section_name] = array();  //Do this explicity to catch empty sections
	  $on = false;
	}
	if ($on) {
	  $key_string = explode("=", $row);
	  //If there's no = sign it can't be a valid key
	  if ( count($key_string) > 1 ) {
	    $key_name = $key_string[0];
	    array_shift($key_string);
	    $key_value = implode("=", $key_string);
	    $ini_parsed[$section_name][$key_name] = trim($key_value);
	  }
	} else {
	  $on = true;
	}
      }
    }
  }
  return $ini_parsed;
}
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top