CodingHowTo

How to Read a Text File Line by Line in PHP

Step 1: Create a Simple Text File

Before we dive into the code, let's create a simple text file named example.txt with some sample content. Here’s how it might look:

Line 1: Hello, World!
Line 2: This is line two.
Line 3: The third line of our example file.
        

Step 2: Read the File Using PHP

Now, let's write a PHP script to read this file line by line. We'll use the built-in PHP function fopen to open the file and fgets to read each line until we reach the end of the file.

<?php
$filename = "example.txt";

// Open the file for reading
$fileHandle = fopen($filename, "r");

if ($fileHandle) {
    while (($line = fgets($fileHandle)) !== false) {
        // Trim any extra whitespace (including newline characters)
        $line = trim($line);
        
        // Process the line here
        echo "$line<br>";
    }

    // Close the file handle
    fclose($fileHandle);
} else {
    echo "Failed to open the file.";
}
?>
        

Step 3: Run Your PHP Script

Save the above PHP code in a file, for example, read_file.php. Place this file in the same directory as your example.txt. You can then run the script using a web server or by executing it from the command line.

php read_file.php
        

Conclusion

In this guide, we've learned how to read a text file line by line in PHP. This method is efficient and suitable for handling files of various sizes. By using the fopen and fgets functions, you can easily process each line of a file, allowing for flexible data handling in your applications.

Remember to always check if the file was successfully opened before attempting to read from it, and don't forget to close the file handle after you're done. Happy coding!

ß