PHP provides various functions to read data from a file. There are different functions that allow you to read all file data, read data line by line and read data character by character.
This function returns the number of bytes read on success, or FALSE and an error on failure. You can hide the error output by adding an "@" in front of the function name.
The PHP fread() function is used to read data of the file. It requires two arguments: file resource and file size.
string fread (resource $file, int $length )
<?php
$filename = "Your Directory Path\fileName.txt";
$fp = fopen($filename, "r");//open file in read mode
$fileContents = fread($fp, filesize($filename));//read file
echo "<pre>$fileContents </pre>";//printing data of file
fclose($fp);//close file
?>
Output :
This is Php Tutorials
Online Learning Website
I Am Software Developer
The PHP fgets() function is used to read a single line from the file.
string fgets ( resource $handle [, int $length ] )
<?php
$fp = fopen("Your Folder Path\myFile.txt", "r");//open file in read mode
echo fgets($fp);
fclose($fp);
?>
Output
this is first line
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 )
<?php
$fp = fopen("Your Directory Path\fileName.txt", "r");//open file in read mode
while(!feof($fp)) {
echo fgetc($fp);
}
fclose($fp);
?>
Output
this is first line this is another line this is third line
© 2024 Easy To Learning. All Rights Reserved | Design by Easy To Learning