What is the best way to delete or overwrite a specific line in a text file using PHP?
When deleting or overwriting a specific line in a text file using PHP, you can read the contents of the file, modify the desired line, and then rewrite the entire file with the updated content. One way to achieve this is by reading the file line by line, keeping track of the line number, and then writing the lines back to the file with the necessary modifications.
<?php
$filename = 'example.txt';
$line_number_to_modify = 3;
$new_line_content = "This is the new content for the line";
$file_contents = file($filename);
$fp = fopen($filename, 'w');
foreach ($file_contents as $line_number => $line_content) {
if ($line_number + 1 == $line_number_to_modify) {
fwrite($fp, $new_line_content . PHP_EOL);
} else {
fwrite($fp, $line_content);
}
}
fclose($fp);
?>
Keywords
Related Questions
- What could be causing the issue of the counterstand being incremented by 2 instead of 1 in the PHP code snippet provided?
- In PHP, what are the best practices for maintaining session consistency and preventing the session_id from being recalculated?
- Is it better to use Active Record for handling database interactions in PHP?