Jump to: navigation, search

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;
?>

Related Links


  1. PHP File Linux vs. Windows
  2. PHP File Information
  3. PHP File Create
  4. PHP File Close
  5. PHP File Read
  6. PHP File Read Reverse
  1. PHP File Write
  2. PHP File Write to end or append to
  3. PHP File Write at Beginning
  4. PHP File Write at specific location
  5. PHP File Truncate
  6. PHP File Replace a specific word
  1. PHP File Replace a specific word with associative array
  2. PHP File Copy File
  3. PHP File Copy Reverse
  4. PHP File Search within file
  5. PHP File Delete File
  6. PHP File Template
  1. PHP File Email Template
  2. PHP File Template with MySQL
  3. PHP File Access with MySQL
Navigation
Web
SQL
MISC
References