|
| HOW TO READ FILES USING THE fgets() FUNCTION IN PHP
You can use the fgets() function to read from a file after it is opened with the fopen() function. This function takes one argument which is the file handle.
The general format is:
fgets(filehandle);
The fgets() function differs from fread() in that it reads a string until it encounters the end of line or end of the file contents, whichever comes first and stops.
Example:
<?
$myFile="test.txt";
$fd=fopen($myFile, "r");
$myLine=fgets($fd);
fclose($fd);
?>
In the above example, the fgets() function will read from the opened test.txt until it encounters an end of line or end of file, whichever comes first and stops. It then stores that string in the $myLine variable. If you echo this variable, you will see the string value.
If you would like PHP to read the entire file until it comes to the end of this file, then use the feof() function with the fgets() function like this:
Example:
<?
$myFile="test.txt";
$fd=fopen($myFile, "r");
while(!feof($fd))
{
$myLine=fgets($fd);
echo $myLine;
}
fclose($fd);
?>
What we are saying above with the while loop is that while it is not end of file, $myLine takes value of a line of the file. Once the end of file is reached, the while loop stops. If you echo $myLine in the loop as above, you will
see the entire contents of this file outputted. You can also use fgets() to read file contents directly into an array - see here.
 |
|
|