In PHP, reading files line by line is a common task, especially when handling large amounts of data. In this article, we will show you how to read a file line by line in PHP and process each line accordingly.
Before we start, we need an example file. Let's assume we have created a file named `file.txt` with the following content:
this is line 1
this is line 2
this is line 3
To read a file line by line, we can use PHP's built-in `fgets()` function. This function reads one line of data from the file pointer until the end of the file is reached.
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// Process each line of data
}
fclose($handle);
} else {
// Handle file open failure
}
In the code above, we open the file using the `fopen()` function, and then use the `fgets()` function to read the file line by line. After reading each line, we can perform further operations on the data. Once the loop ends, we close the file using the `fclose()` function.
Here is a complete example that demonstrates how to output each line of the file to the screen:
<?php
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line . "<br>";
}
fclose($handle);
} else {
echo "Failed to open the file";
}
?>
In this example, after reading each line of data, we output it using a `
` tag for line breaks. You can save this code as a PHP file and view the output in your browser.
This article covered how to read a file line by line in PHP. By mastering the use of the `fgets()` function, you can efficiently process each line of data in a file. Whether you are working with log files, importing data, or performing other file operations, this technique will greatly improve your workflow in PHP development.