php - file read
My apologies for taking so long to
actually get to the point where you get information from files. In this lesson
we will teach you how to read data from a file using various PHP functions.
php - file open: read
Before we can read information from a file we have to use the
function fopen to open the file for reading. Here's
the code to read-open the file we created in the PHP File Write lessons.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
php - file read: fread function
The fread function is the staple for getting
data out of a file. The function requires a file handle, which we have, and an
integer to tell the function how much data, in bytes, it is supposed to read.
One character is equal to one byte. If you wanted to read the
first five characters then you would use five as the integer.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
echo $theData;
If you wanted to read all the data from the file, then you need to
get the size of the file. The filesize function returns the length of a file,
in bytes, which is just what we need! The filesize function requires the name of the file
that is to be sized up.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
php - file read: gets function
PHP also lets you read a line of data at a time from a file with
the gets function. This can or cannot be useful
to you, the programmer. If you had separated your data with new lines then you
could read in one segment of data at a time with the gets function.
Lucky for us our "testFile.txt" file is separated by new
lines and we can utilize this function.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
Comments
Post a Comment
Thank you for your Comment