How can you overwrite a specific line in a file using PHP?

To overwrite a specific line in a file using PHP, you can read the contents of the file, modify the specific line you want to overwrite, and then write the updated contents back to the file. You can achieve this by using functions like file(), fopen(), fseek(), and fwrite().

$file = 'example.txt';
$lineNumber = 2; // Line number to overwrite
$newContent = "This is the new content for line 2\n";

$lines = file($file);
$lines[$lineNumber - 1] = $newContent;

$handle = fopen($file, 'w');
fwrite($handle, implode('', $lines));
fclose($handle);