How can PHP be used to write to the beginning of a text file instead of appending to the end?

To write to the beginning of a text file in PHP instead of appending to the end, you can read the existing content of the file, prepend the new data to it, and then write the updated content back to the file.

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

// Read existing content from the file
$existingData = file_get_contents($file);

// Prepend the new data to the existing content
$newData = $data . $existingData;

// Write the updated content back to the file
file_put_contents($file, $newData);