What are the potential pitfalls of using file() to read a TXT file in PHP?
Using the file() function to read a TXT file in PHP can potentially lead to performance issues, as it reads the entire file into an array in memory. This can be problematic for large files, consuming a lot of memory and potentially causing the script to run out of memory. To solve this issue, it's better to use fopen() and fread() functions to read the file line by line or in chunks.
$filename = 'example.txt';
$handle = fopen($filename, 'r');
if ($handle) {
while (($line = fgets($handle)) !== false) {
// Process each line as needed
}
fclose($handle);
} else {
echo "Error opening the file.";
}