Home >Backend Development >PHP Tutorial >How to read a plain text file line by line with PHP?
Reading Plain Text Files with PHP
Question:
You have a plain text file with lines of data on a server. How can you read all the information from the file line by line using PHP?
Answer:
To read a plain text file line by line with PHP, follow these steps:
<code class="php">$fh = fopen('filename.txt','r'); while ($line = fgets($fh)) { // Perform any necessary operations with the line // For example, echo $line; } fclose($fh);</code>
In this code, fopen() opens the file and returns a file handler. The while loop then reads each line from the file using fgets() and places it in the $line variable. You can perform any necessary actions with each line within the loop. After reading all the lines, fclose() closes the file.
Note: As mentioned in the provided answer, be aware of potential end of line issues with Macs when using fgets(). See the PHP manual for more details.
The above is the detailed content of How to read a plain text file line by line with PHP?. For more information, please follow other related articles on the PHP Chinese website!