How does the use of fopen() in PHP differ from other methods for deleting a line from a text file?

When using fopen() in PHP to delete a line from a text file, you need to read the file line by line, skip the line you want to delete, and then write the remaining lines to a new file. This process involves more steps compared to other methods like file_get_contents() and file_put_contents(), which can read the entire file into memory, modify it, and then overwrite the original file. However, using fopen() allows for more control and flexibility when working with large files or specific line deletions.

$filename = 'example.txt';
$line_number = 3; // Line number to delete

$source = fopen($filename, 'r');
$target = fopen('temp.txt', 'w');

$current_line = 0;
while (!feof($source)) {
    $current_line++;
    $line = fgets($source);
    
    if ($current_line != $line_number) {
        fwrite($target, $line);
    }
}

fclose($source);
fclose($target);

unlink($filename);
rename('temp.txt', $filename);