Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here


Parsing an INI File by skiflyer
Posted: 23 May 03

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.

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];
        $key_value = implode("=", $key_string);
        $ini_parsed[$section_name][$key_name] = trim($key_value);
    } else {
      $on = true;
  return $ini_parsed;

Back to PHP FAQ Index
Back to PHP Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close