How can PHP developers efficiently prepend data to a text file without risking memory issues?

Prepending data to a text file in PHP can be done efficiently by using the "fopen" function with the "r+" mode to open the file for reading and writing. This allows you to move the file pointer to the beginning of the file and write new data without loading the entire file into memory. By using this method, you can efficiently prepend data to a text file without risking memory issues.

$file = 'example.txt';
$data = "New data to prepend\n";

$handle = fopen($file, 'r+');
$existingData = fread($handle, filesize($file));

rewind($handle);
fwrite($handle, $data . $existingData);

fclose($handle);