PHP Tutorial
PHP provides various functions to read data from file.
The available PHP file read functions are given below.
First create a text file with file1.txt file name and put this content in the file.
Code Now
Code Tomorrow
Code Always
The PHP fread() function is used to read data of the file. It requires two arguments: file resource and file size.
string fread (resource $handle , int $length )
$handle represents file pointer that is created by fopen() function.
$length represents length of byte to be read.
Lets put this into example.
<?php
$myfile = "c:\\file1.txt";
//open file in read mode
$fp = fopen($myfile, "r");
//read file
$contents = fread($fp, filesize($myfile));
//printing data of file
echo "<pre>$contents</pre>";
fclose($fp);//close file
?>
This will produce the following result −
Code Now
Code Tomorrow
Code Always
The PHP fgets() function is used to read single line from the file.
string fgets ( resource $handle [, int $length ] )
$handle represents file pointer that is created by fopen() function.
$length represents length of byte to be read.
Lets put this into example.
<?php
//open file in read mode
$fp = fopen("c:\\file1.txt", "r");
echo fgets($fp);
fclose($fp);
?>
This will produce the following result −
Code Now
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.
string fgetc ( resource $handle )
$handle represents file pointer that is created by fopen() function.
Lets put this into example.
<?php
$fp = fopen("c:\\file1.txt", "r"); //open file in read mode
while(!feof($fp)) {
echo fgetc($fp);
}
fclose($fp);
?>
This will produce the following result −
Code Now Code Tomorrow Code Always