Friday, September 29, 2017

PHP Read File

PHP provides various functions to read data from file. These functions allow you to read all file data, read data line by line and read data character by character.

The available PHP file read functions are as follows :

  1. fread()
  2. fgets()
  3. fgetc()
File to read using these functions :
Skptricks PHP Read File

PHP Read File - fread() :
The PHP fread() function is used to read data of the file. It requires two arguments: file resource and file size.

Syntax:
string fread (resource $handle , int $length )

$handle represents file pointer that is created by fopen() function.
$length represents length of byte to be read.

Example :
<?php    
$filename = "FileToRead.txt";    
//open file in read mode 
$fp = fopen($filename, "r");   
//read file      
$contents = fread($fp, filesize($filename));
//printing data of file    
echo "<pre>$contents</pre>";
//close file   
fclose($fp); 
?>
Output:
-----------------------------

Welcome to skptricks
Reading the content number one.
Reading the content number two.
Reading the content number three.
Reading the content number four.
Reading the content number five.

PHP Read File - fgets()
The PHP fgets() function is used to read single line from the file.

Syntax:
string fgets ( resource $handle [, int $length ] )

Example :
<?php    
//open file in read mode    
$fp = fopen("FileToRead.txt", "r");
//printing data of file
echo fgets($fp);  
// closing file
fclose($fp);  
?>
Output:
----------------------------
Welcome to skptricks

PHP Read File - fgetc()
The PHP fgetc() function is used to read single character from the file. To get all data using fgetc() function, use !feof() function inside the while loop.

Syntax:
string fgetc ( resource $handle )

Example :
<?php  
//open file in read mode  
$fp = fopen("FileToRead.txt", "r");   
// Reading data character by character using loop 
while(!feof($fp)) {  
  echo fgetc($fp);  
}  
//closing file
fclose($fp);  
?>
Output:
-----------------
Welcome to skptricks Reading the content number one. Reading the content number two. Reading the content number three. Reading the content number four. Reading the content number five.


No comments:

Post a Comment