In PHP, reading a file means accessing its contents and retrieving data stored within it.
- PHP provides various functions to read files, making it possible to access file data for displaying, processing, or performing specific operations.
The following built-in functions in PHP’s library can help us perform the read operation:
- fgets() — Reads a single line from a file
- fread() — Reads a specified number of bytes from a file
- fgetc() — Reads a single character from a file
fgets()
// Open the file
$file = fopen("example.txt", "r");
if ($file) {
// Read each line one by one
while (($line = fgets($file)) ! = = false) {
echo $line . "<br>";
}
fclose($file);
} else {
echo "Unable to open the file.";
}
fread()
This function is efficient for handling large files as it reads the file in specified chunks.
$file = fopen("example.txt", "r");
if ($file) {
// Read file in 1024-byte chunks
while (!feof($file)) {
$chunk = fread($file, 1024);
echo $chunk;
}
fclose($file);
} else {
echo "Unable to open the file.";
}
fgetc()
$file = fopen("example.txt", "r");
if ($file) {
// Read one character at a time
while (($char = fgetc($file)) ! = = false) {
echo $char;
}
fclose($file);
} else {
echo "Unable to open the file.";
}