How can PHP be used to efficiently manage and update specific lines of text within a file?

To efficiently manage and update specific lines of text within a file using PHP, you can read the file line by line, identify the specific line you want to update, make the necessary changes, and then write the updated content back to the file. This can be achieved by using functions like fopen, fgets, fwrite, and fclose in PHP.

<?php
$filename = 'example.txt';
$line_number = 3; // Line number to update
$new_content = 'New content for line 3';

$file = fopen($filename, 'r');
$temp_file = fopen('temp.txt', 'w');

$current_line = 0;
while (!feof($file)) {
    $current_line++;
    $line = fgets($file);
    if ($current_line == $line_number) {
        fwrite($temp_file, $new_content . PHP_EOL);
    } else {
        fwrite($temp_file, $line);
    }
}

fclose($file);
fclose($temp_file);

rename('temp.txt', $filename);
?>