Reading from Files
Reading from Files
You can read from files opened in r, r+, w+, and a+ mode. The feof function is used to determine if the end of file is true.
if ( feof($fp) )
echo "End of file<br>";
The feof function can be used in a while loop, to read from the file until the end of file is encountered. A line at a time can be read with the fgets function:
while( !feof($fp) ) {
// Reads one line at a time, up to 254 characters. Each line ends with a newline.
// If the length argument is omitted, PHP defaults to a length of 1024.
$myline = fgets($fp, 255);
echo $myline;
}
You can read in a single character at a time from a file using the fgetc function:
while( !feof($fp) ) {
// Reads one character at a time from the file.
$ch = fgetc($fp);
echo $ch;
}
You can also read a single word at a time from a file using the fscanf function. The function
takes a variable number of parameters, but the first two parameters are mandatory. The first
parameter is the file handle, the second parameter is a C-style format string. Any parameters
passed after this are optional, but if used will contain the values of the format string.
$listFile = "list.txt"; // See next page for file contents
if (!($fp = fopen($listFile, "r")))
exit("Unable to open $listFile.");
while (!feof($fp)) {
// Assign variables to optional arguments
$buffer = fscanf($fp, "%s %s %d", $name, $title, $age);
if ($buffer == 3) // $buffer contains the number of items it was able to assign
print "$name $title $age<br>\n";
}
Here is the file
list.txt:
Dave Programmer 34
Sue Designer 21
Lisa Programmer 29
Nigel User 19
You can also store the variables in an array by omitting the optional parameters in fscanf:
while (!feof($fp)) {
$buffer = fscanf($fp, "%s %s %d"); // Assign variables to an array
// Use the list function to move the variables from the array into variables
list($name, $title, $age) = $buffer;
print "$name $title $age<br>\n";
}
You can read in an entire file with the fread function. It reads a number of bytes from a file, up to the end of the file (whichever comes first). The filesize function returns the size of the file in bytes, and can be used with the fread function, as in the following example.
$listFile = "myfile.txt";
if (!($fp = fopen($listFile, "r")))
exit("Unable to open the input file, $listFile.");
$buffer = fread($fp, filesize($listFile));
echo "$buffer<br>\n";
fclose($fp);
You can also use the file function to read the entire contents of a file into an array instead of opening the file with fopen:
$array = file(‘filename.txt’);
Each array element contains one line from the file, where each line is terminated by a newline.