Is counting the number of lines in a text file using PHP a recommended approach for targeting specific lines of content?

Counting the number of lines in a text file using PHP is not the recommended approach for targeting specific lines of content as it can be inefficient for large files. Instead, it is better to read the file line by line until the desired line is reached. This approach is more efficient and allows for better control over the specific lines of content being targeted.

$filename = 'example.txt';
$targetLine = 5; // Change this to the line number you want to target

$handle = fopen($filename, 'r');
if ($handle) {
    $currentLine = 0;
    while (($line = fgets($handle)) !== false) {
        $currentLine++;
        if ($currentLine == $targetLine) {
            echo $line;
            break;
        }
    }
    fclose($handle);
} else {
    echo "Error opening the file.";
}