What are some best practices for updating existing data in a file without overwriting it in PHP?
When updating existing data in a file without overwriting it in PHP, one common approach is to read the file into memory, make the necessary changes, and then rewrite the entire file with the updated data. However, this can be inefficient for large files. A better approach is to use a combination of file reading, data manipulation, and file writing functions to update only the specific parts of the file that need to be changed.
// Read the contents of the file into an array
$data = file('data.txt');
// Update the specific data in the array
foreach ($data as $key => $line) {
if (strpos($line, 'old_data') !== false) {
$data[$key] = str_replace('old_data', 'new_data', $line);
}
}
// Write the updated data back to the file
file_put_contents('data.txt', implode('', $data));