What are some best practices for opening and reading a text file in PHP before extracting specific data?
When opening and reading a text file in PHP before extracting specific data, it is essential to follow best practices to ensure efficient and error-free processing. One common approach is to use the `fopen()` function to open the file, check if the file was opened successfully, read its contents using `fgets()` or `fread()`, and then close the file using `fclose()` to free up system resources.
$filename = 'data.txt';
$file = fopen($filename, 'r');
if ($file) {
while (($line = fgets($file)) !== false) {
// Process each line of the file here
echo $line;
}
fclose($file);
} else {
echo "Error opening file.";
}