The following function demonstrates how to read in a local file with PHP. You must first use the fopen() function to open the file handle. This tells PHP where to look to find this file. After that, it is simply a matter of iterating over the file until there are no more lines. The feof() function tests if it has reached the end of the file yet - returning true if it has and false if there is still more to be read. Once we know there is another line to be read in, fgets() reads in the line for us into a slot of the array. Once all the data is read, fclose() tells PHP to close the file handle.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/** * Reads in the a file to an array * @param $filename the name of the file to read * @return if the file exists, it returns an array of the file contents */ function read($filename){ $config = array(); if(file_exists($filename)){ $stdin = fopen($filename, 'r') or die("cannot find file"); // initialize the scanner $i = 0; while(! feof($stdin)){ $config[$i] = fgets($stdin); $i++; } fclose($stdin); return $config; } else { // the file did not exist, return null return null; } } |




