What potential pitfalls should be considered when using the file() function to read a text file in PHP?
When using the file() function in PHP to read a text file, it's important to consider potential pitfalls such as memory usage for large files and error handling for file not found or permission issues. To mitigate these risks, you can use error handling to catch any exceptions that may arise and handle them gracefully. Additionally, you can read the file line by line instead of loading the entire file into memory at once.
$file = 'example.txt';
if (file_exists($file)) {
$lines = file($file, FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) {
// Process each line as needed
}
} else {
echo 'File not found.';
}