Skip to content
PHP Logo

What are some potential pitfalls of using PHP to read and output specific lines from a .txt file?

One potential pitfall of using PHP to read and output specific lines from a .txt file is that the file may be too large to load entirely into memory, causing performance issues. To avoid this, you can read the file line by line and only output the specific lines you need.

php
<?php
$filename = 'example.txt';
$lines_to_output = [2, 5, 8]; // Specific lines to output

$handle = fopen($filename, "r");
if ($handle) {
    $line_number = 1;
    while (($line = fgets($handle)) !== false) {
        if (in_array($line_number, $lines_to_output)) {
            echo $line;
        }
        $line_number++;
    }

    fclose($handle);
} else {
    echo "Error opening the file.";
}
?>