phpconfigurationtext-parsingfileparsing

How to parse a config file with non-standard formatting?


I have the following notepad file;

dbName:              
 
tableName:       

numberOfFields:

I am trying to write a php app which assigns the value of dbName to $dbName, tableName to $tableName and numberOfFields to $numFields.

My code is:

$handle = @fopen("config.txt", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);
        list($dbName, $tableName, $numFields) = explode(":", "$buffer");
    }
    fclose($handle);
}

however, ":" doesn't work as there are line breaks in between dbName and table Name. How do I explode $buffer, keeping the line breaks in the notepad file?


Solution

  • Have a look at the file function. It takes care of opening and reading the file, and returns an array of lines from the file. You could then iterate through the array and operate on each line individually.

    http://us.php.net/manual/en/function.file.php