This section contains the detail about reading file in PHP.
File Read
In the above sections, we have discussed about how to create, open, close & write to a file. In the below section, you will learn how to read a file.
To read a file, we have three main functions or methods- fread, fgets & fgetc.
Reading a file till specified character
For this purpose, we have fread() function. The fread() function takes two arguments - first the file handle & other is an integer to tell the function how much data, in bytes, it is supposed to read.
The Data inside testFile.txt is given below :
Devmanuals
PHP Tutorial
Given below example read first 7 characters from the file :
<?php // PHP code to read a file $myFileName = 'C:\testFile.txt'; $myFileHandle = fopen($myFileName, 'r') or die("cant open file"); $dataRead = fread($myFileHandle, 7); fclose($myFileHandle); echo $dataRead; ?>
Output
Devmanu
Read whole file using fread()
Given below example :
<?php // PHP code to read a file $myFileName = 'C:\testFile.txt'; $myFileHandle = fopen($myFileName, 'r') or die("cant open file"); $dataRead = fread($myFileHandle,filesize($myFileName)); fclose($myFileHandle); echo $dataRead; ?>
Output :
Devmanuals PHP Tutorial
Reading a File Line by Line
You can make you code to read a file line by line using fgets() as follows:
<?php $myFileName = 'C:\testFile.txt'; $myFileHandle = fopen($myFileName, 'r') or die("cant open file"); //Output a line until the end of file while(!feof($myFileHandle)) { echo fgets($myFileHandle). "<br />"; } fclose($myFileHandle); ?>
Output :
Devmanuals
PHP Tutorial
Reading a File Character by Character
You can make your code to read a file line by line using fgetc() as follows :
<?php $myFileName = 'C:\testFile.txt'; $myFileHandle = fopen($myFileName, 'r') or die("cant open file"); while (!feof($myFileHandle)) { echo fgetc($myFileHandle); } fclose($myFileHandle); ?>
Output :
Devmanuals PHP Tutorial
[ 0 ] Comments