0% found this document useful (0 votes)
63 views

PHP - File Read: Gets Function

The document discusses reading files in PHP. It shows how to open a file, read the entire contents into a variable using fread, and echo it. It then demonstrates using fgets to read a file line by line into a variable, echoing the first line. Fgets searches for the first newline character in the file.

Uploaded by

Anil Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views

PHP - File Read: Gets Function

The document discusses reading files in PHP. It shows how to open a file, read the entire contents into a variable using fread, and echo it. It then demonstrates using fgets to read a file line by line into a variable, echoing the first line. Fgets searches for the first newline character in the file.

Uploaded by

Anil Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 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