Categories
PHP

Reading files by line or by character

In this tutorial, you will learn how to parse large files, keeping the system’s memory safe. We will use the PHP functions (fgets, fgetc, and fread) that can read chunks of the file content at a time.

The disadvantage of file_get_contents() and file() is that they read the whole file into memory. With huge files, it’s preferable to use functions that process only a part of a file at a time.

fgets() – Read files by line

The fgets() function reads the file until the next newline character (or carriage return) is found, it returns the current line.

Open the file with fopen(), then call fgets() as long as data is returned (a while loop is convenient here) and output the data:

<?php
 $fp = fopen('file.txt', 'r');
 while (!feof($fp)) {
  $line = fgets($fp);
  echo $line.'<br>';
 }
 fclose($fp);

The fgets($fp); statement returns the current line and fgets($fp, 20); statement returns the 20 characters. The fgets() function can return as many characters as are provided in its second parameter but, at most, all characters until the end of the current line.

<?php
 $fp = fopen('file.txt', 'r');
 while (!feof($fp)) {
  $line = fgets($fp, 20);
  echo $line.'<br>';
 }
 fclose($fp);

fgetc() – Read files by character

Open the file with fopen(), then call fgetc() as long as data is returned (a while loop is convenient here) and output the data. fgetc() returns a string containing a single character read from the file pointed to by stream. Returns false on EOF (end of file).

<?php
 $fp = fopen('file.txt', 'r');
 while (!feof($fp)) {
  $character = fgetc($fp);
  echo $character;
 }
 fclose($fp);

The feof() function terminates the while loop when the end-of-file pointer is encountered.

fread() – binary-safe file read

The fread() function reads a string of characters from a file, it requires two arguments: a file handle and the number of characters to read:

<?php
 $fp = fopen('file.txt', 'r');
 while (!feof($fp)) {
  $characters = fread($fp, 100);
  echo $characters;
 }
 fclose($fp);

Example: Read the entire contents of the file with fread() function

Use the filesize function to read the entire file with fread function:

<?php
 $file = 'file.txt';

 $fp = fopen($file, 'r');
 if ($fp === false) {
  die ("Unable to open $file");
 }
 
 $size = filesize($file);
 $data = '';
 
 if ($size > 0 ){
  $data = fread($fp, $size);
 }

 if ($data === false) {
  die ("Unable to read $file");
 }
 echo $data;
 fclose($fp);

Working with Files in PHP: