Reading Data From a File Using PHP

Introduction

In this article I will demonstrate all the possible ways of reading data from a file. Reading content from a file is usually a 3 step process.

Syntax

string fread( resource $fileHandle, int length)

  1. <?php  
  2. $file = 'C:\helloWorld.txt' or die('Could not open file!');  
  3. $fHandle = fopen($file'r'or die('Could not open file!');  
  4. $data = fread($fHandlefilesize($file)) or die('Could not read file!');  
  5. fclose($fHandle);  
  6. echo $data;  
  7. ?>  
Step 1: Open a file.

PHP needs a file handle to read data from a file. This file handle can be created with the fopen() function. The fopen() function takes two arguments, the first argument takes the name of the file path and the second argument takes the "mode". The following are the three modes in the fopen() function.

'r': opens a file in read mode.
'w': opens a file in write mode, destroying existing file contents
'a': opens a file in append mode, retaining the file contents.

 

Step 2: Read the file content.

The fread() function reads the contents of a file if the fopen() function is successful. The fread() function also takes two arguments. The first argument takes a file handle and the second argument takes the size of the file using the filesize() function.

filesize(): This function returns the size of the file in the bites.

Step 3: Close the file.

The fclose() function closes a file. This is good programming to close the file after use. This is strictly necessary to close the file.

Output Screen

This is the common text file that I used in all three demo examples. 

fileHandlingTextFile


fileHandlingExample
Another way

There is alternative way to read the file using the file() function. The file() function reads the entire file into an array and we can display it using the foreach() loop.

  1. <?php  
  2. $file = 'C:\helloWorld.txt' or die('Could not read file!');  
  3. $Data = file($fileor die('Could not read file!');  
  4. foreach ($Data as $n) {  
  5.        echo $n;  
  6. }  
  7. ?>  

 


fileHandlingExample 
One more way

The file_get_contents() function reads the entire file into a string. This is the most easy way to read a file.
  1. <?php  
  2. $file 'C:\helloWorld.txt';  
  3. $data =file_get_contents($fileor die('Could not read file!');  
  4. echo $data;  
  5. ?>  
fileHandlingExample 
Summary

In this article I tried to show all three ways of reading a file using PHP. The first fread() function is a three way process; open the file, read the file and close the file. The second is the file() function that returns an array of strings. And the most useful and easy to remember function is one of my favourite functions, file_get_contents()

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now