Home > Backend Development > PHP Tutorial > How to Count Lines in Large Text Files Efficiently in PHP?

How to Count Lines in Large Text Files Efficiently in PHP?

Linda Hamilton
Release: 2024-11-04 19:33:02
Original
224 people have browsed it

How to Count Lines in Large Text Files Efficiently in PHP?

Counting Text File Lines Efficiently for Large Files

Problem:

PHP scripts can encounter memory issues when attempting to count the lines of large text files (2MB ). A common approach using file() and count() may trigger a fatal memory error.

Solution:

To avoid memory exhaustion, consider adopting a more efficient approach:

<code class="php">$file = "largefile.txt";
$linecount = 0;
$handle = fopen($file, "r");

while (!feof($handle)) {
  $line = fgets($handle);
  $linecount++;
}

fclose($handle);

echo $linecount;</code>
Copy after login

This approach uses fgets() to read a single line at a time, which reduces memory usage.

For extremely long lines, a variation using substr_count() can be used to count end-of-line characters:

<code class="php">$handle = fopen($file, "r");

while (!feof($handle)) {
  $line = fgets($handle, 4096);
  $linecount = $linecount + substr_count($line, PHP_EOL);
}

fclose($handle);

echo $linecount;</code>
Copy after login

By implementing these techniques, PHP scripts can efficiently count the lines of large text files while conserving memory.

The above is the detailed content of How to Count Lines in Large Text Files Efficiently in 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