What is the difference between using fopen and file_get_contents in PHP to read a file?
The main difference between using fopen and file_get_contents in PHP to read a file is that fopen is used to open a file resource, allowing for more control over reading and writing operations, while file_get_contents reads the entire contents of a file into a string variable in one step. If you need to perform more complex operations on a file, such as reading it line by line or writing to it, fopen is the better choice. However, if you simply need to read the contents of a file into a variable, file_get_contents is more convenient.
// Using fopen to read a file
$filename = 'example.txt';
$handle = fopen($filename, 'r');
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
} else {
echo 'Error opening the file.';
}
// Using file_get_contents to read a file
$filename = 'example.txt';
$file_contents = file_get_contents($filename);
if ($file_contents !== false) {
echo $file_contents;
} else {
echo 'Error reading the file.';
}