PHP

 Home  Computers & Internet  Web Programming PHP
What is PHP?
Echo
Comments
Variables
Constants
Data Types
number_format()
Character Strings
Mathematical Operators
Comparison Operators
Logical Operators
Joining Strings
explode()
implode()
strtolower()
strtoupper()
strlen()
ucfirst()
ucwords()
strrev()
str_replace()
str_repeat()
trim()
strip_tags()
addslashes()
stripslashes()
strpos()
strrpos()
nl2br()
isset()
unset()
empty()
POST
GET
If Statements
If Else Statements
Elseif Statements
Switch Statements
For Loops
While Loops
Do While Loops
Foreach Loops
File Create
File Open
File Read
File Write
File Delete
fgets()
file_get_contents()
Date & Time
$_SERVER
Sessions
Cookies
Arrays

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.



Home | Privacy Policy | Terms Of Use | Contact Us