Thursday, 28 August 2008

PHP: Read File of Name Value Pair Parameters into an Array

This is a simple code snippet, that can be dropped into any code, to read name value pair parameters from a file into an array, so that the parameter name is the array key.

Example params.txt file extract:

PHP code snippet:
$param = array();
$paramsFile = fopen('params.txt','r');
$buffer = fgets($paramsFile);
list($name,$value) = split('=',trim($buffer));
$param[$name] = $value;
fclose ($paramsFile);

The array can then be referenced as:
echo $param['height'];

To use the tab character as the seperator instead of (=) equals, change the list line to:
list($name,$value) = split("\t",trim($buffer));


No comments: