PHP File Read
From w3cyberlearnings
Contents |
PHP Read A File
Read a file content line by line uses loop; read a file content at once uses fread() function.
Syntax file
Use file() function when the file is not more than 10M. For larger file uses fopen().
file(filename);
Syntax fopen
fopen(filename);
Syntax fread
- Binary safe file read.
fread(filehandle,length);
File Content (fruits.txt)
Apple is red. Apple is also green. Apple is not blue. Orange is yellow. Orange is not blue. Orange is red.
Example 1: file()
- Use file and read file a line at a time.
<?php $my_file = 'fruits.txt'; $lines = file($my_file); foreach ($lines as $line) { echo $line . "<br/>"; } ?>
Output
Apple is red. Apple is also green. Apple is not blue. Orange is yellow. Orange is not blue. Orange is red.
Example 2: fopen()
- fgets() function read at the file pointer.
<?php $my_file = 'fruits.txt'; $lines = fopen($my_file, 'r') or exit('unable to read'); while (!feof($lines)) { echo fgets($lines); echo "<br/>"; } fclose($lines); ?>
Output
Apple is red. Apple is also green. Apple is not blue. Orange is yellow. Orange is not blue. Orange is red.
Example: fread()
- Read file content use fread() function.
<?php $file_name = 'fruits.txt'; $file_handler = fopen($file_name, 'r') or exit('can not open the file'); $file_content = fread($file_handler, filesize($file_name)); fclose($file_handler); echo $file_content; ?>