The Mighty Text File

Don’t get me wrong, databases are cool. As a PHP programmer and web developer, I use relational databases every day, and for complex data sets, searching or sorting, nothing is better. The problem is that as soon as you are using a database, no matter how small, you suddenly have a whole bunch of extra overhead. You need to have a database server, write SQL queries, optimize results, and (my least favorite) build some sort of admin interface to actually add/remove/edit the data. If you are just doing a simple project, all this seems like a lot of work for a very small result. Enter the text file.

For many purposes, storing the data in a flat text file can be just as effective as a full database, and it is so much quicker and easier to work with. Want to add an item? Open the text file up in Notepad and add it in. Same for removing and editing. No muss, no fuss, no admin interface needed. For the first 3 years or so, this is how LoadingReadyRun.com operated. The one downside of using a text file for this kind of project is that is can be a little tricky to read back in a useful way, my first text file base projects had a lot of file[0].” “.file[2]. Which works fine, but is a little opaque if you don’t know the exact format of the text file.

To solve this problem, I wrote the following handy little function and have used it in a bunch of projects since:

 <?php

function parse_data_file($path,$delim='|'){
	$items = file($path);
	$headers = array_shift($items);
	$headers = explode($delim,trim($headers));

	$out = array();

	foreach($items as $row => $item){
		$item_array = explode($delim,trim($item));
		foreach($item_array as $col => $field){
			$out[$row][$headers[$col]] = $field;
		}
	}
	return $out;
}

?>

When given the path to a text file, this function returns all the data in an associative array with the column names based on the first line of the text file.

For example, given the following text file:

first_name|last_name|phone|fax
Bob|Fredson|5551235678|5551235678
Fred|Johnosn|5551875678|5551274678
John|Bobson|5551231178|555123444

The function would return the following array:

array {
	[0] => array {
		[first_name] => Bob
		[last_name] => Fredson
		[phone] => 5551235678
		[fax] => 5551235678
		}
	[1] => array {
		[first_name] => Fred
		[last_name] => Johnosn
		[phone] => 5551875678
		[fax] => 5551274678
		}
	[2] => array {
		[first_name] => John
		[last_name] => Bobson
		[phone] => 5551231178
		[fax] => 5551234445
		}
	}

Note: The function defaults to the pipe character, “|”, as a delimiter. I chose this character because it will probably never come up in the data and it also looks as much like a seperator as possible. If you want to use a different delimiter (“;” or “#”, for example) just pass it as the second parameter.

Comments (7)