PHP - Read in a file

(1 vote, average 4.00 out of 5)

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;
        }       
}
Partner Links:
Last Updated on Saturday, 17 July 2010 23:48  
Related Articles

» How to Move (or 'Cut and Paste') a File in Linux

Moving a file in linux is as easy as using the mv command:mv filename.txt foo/bar/newname.txtThe command above would move a file named filename.txt into the bar directory with a new name (newname.txt). If you only specify the directory, the name of the file will not change.

» Find and Replace Text in Multiple Files

Sometimes it is useful to be able to replace a certain piece of text in multiple files, even across multiple folders. Opening each file and using find/replace is tedious. Fortunately, there is a much easier way using the sed and grep utilities. For Windows users, please to get these programs on your system. Linux and Mac OS X users will already have these programs pre-installed.Launch a terminal window, and cd to the root directory where all of these files and folders exist. Once in the...

» How to Fix the PS2 Disc Read Error

Although the Playstation 2 is a system well-known for it's longevity and durability, the fact that it is over a decade old means that it inevitably will have a few issues.  The most common of which is the infamous disc read error.  This is characterized by entering a disc into the PS2, but instead of booting in the game, an error message comes up saying the disc could not be read or the disc was not recognized. There are several ways to fix it, listed below in order of least to most...