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

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 19:33:02151browse

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>

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>

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!

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