What are the best practices for reading and manipulating text files in PHP?

When reading and manipulating text files in PHP, it's important to use the appropriate file handling functions and techniques to ensure efficient and accurate processing. Best practices include using functions like fopen(), fread(), fwrite(), and fclose() to open, read, write, and close files respectively. Additionally, it's important to handle errors and exceptions properly to prevent data loss or corruption.

// Example of reading and manipulating a text file in PHP

// Open the file for reading
$filename = 'example.txt';
$handle = fopen($filename, 'r');

// Check if the file was opened successfully
if ($handle) {
    // Read the contents of the file
    $contents = fread($handle, filesize($filename));
    
    // Manipulate the contents (e.g. replace a string)
    $manipulatedContents = str_replace('old string', 'new string', $contents);
    
    // Open the file for writing
    $writeHandle = fopen($filename, 'w');
    
    // Write the manipulated contents back to the file
    fwrite($writeHandle, $manipulatedContents);
    
    // Close the file handles
    fclose($handle);
    fclose($writeHandle);
} else {
    echo 'Error opening the file.';
}