Home > Article > Backend Development > How to Count Lines in Large Text Files Efficiently in PHP?
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!