Home  >  Article  >  Backend Development  >  How to read a plain text file line by line with PHP?

How to read a plain text file line by line with PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 08:42:31922browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn