How can PHP be used to read and write data to a text file efficiently?

To efficiently read and write data to a text file in PHP, you can use the file functions provided by PHP such as fopen, fread, fwrite, and fclose. These functions allow you to open a file, read its contents, write new data, and close the file to ensure data integrity.

// Open a file for reading and writing
$file = fopen("data.txt", "r+");

// Read data from the file
$data = fread($file, filesize("data.txt"));
echo $data;

// Write new data to the file
fwrite($file, "New data to write");

// Close the file
fclose($file);