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

Barbara Streisand
Release: 2024-10-27 08:42:31
Original
918 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!