You are on page 1of 1

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;

Display:
Floppy Jalopy Pointy Pinto

Note: It is all on one line because our "testFile.txt" file did not have a <br /> tag to create an HTML line
break. Now the entire contents of the testFile.txt file is stored in the string variable $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;

testFile.txt Contents:
Floppy Jalopy

The fgets function searches for the first occurrence of "\n" the newline character. If you did not write
newline characters to your file as we have done in File Write, then this function might not work the way you
expect it to.

You might also like