PHP
1. File specifies the filename to read content
2. Length Optional parameter specifies the number of bytes to read from the file.
Advertisement
Syntax
PHP fgets() function uses the following syntax.
fgets(file, length)
Example – Read a single line
Below are two examples of a reading single line from a file. Use this example to read the complete first-line content from a file.
1 2 3 4 5 6 | <?php $fn = fopen("/var/data/myfile.txt","r"); $result = fgets($fn); echo $result; fclose($fn); ?> |
Instead of a line, you can also define the number of bytes to read from a file:
1 2 3 4 5 6 | <?php $fn = fopen("/var/data/myfile.txt","r"); $result = fgets($fn, 20); echo $result; fclose($fn); ?> |
Example – Read All Lines
Use this example to read all lines from files one by one using for loop. Use PHP feof() function to find the end of the file.
1 2 3 4 5 6 7 8 9 10 | <?php $fn = fopen("/var/data/myfile.txt","r"); while(! feof($fn)) { $result = fgets($fn); echo $result; } fclose($fn); ?> |
3 Comments
good article, thanks man!
$file should read $fn
$file not define …