Last updated on February 27th, 2022 at 07:56 am

Display text file or text data base line by line and delete certain lines using php. This script has the ability to read the text file and append a “Delete” hyperlink at the end of each line so that you can selectively delete lines.

NOTE:-My text file name is mail_list.txt
Create a file with name del.php and add the below code. Save it and run it against a PHP web server.
If the file is empty it will display an error message.

<?php
$delete = $_GET['delete'];
$file_name = "mail_list.txt";
$size = filesize($file_name);
$textFile = file($file_name);
$lines = count($textFile);
if($size == "0")
{
echo "Nothing to display, Seems like file is empty. Try adding some data to it!!!";
exit;
}
if($delete != "" && $delete >! $lines || $delete === '0') {
    $textFile[$delete] = "";
    $fileUpdate = fopen($file_name, "wb");
    for($a=0; $a< $lines; $a++) {
           fwrite($fileUpdate, $textFile[$a]);
    }
    fclose($fileUpdate);
   header("Location:delete.php");
   exit;
} else

foreach($textFile as $key => $val) {
$line = @$line . $val . "<a href =?delete=$key> Delete </a><br />";
}
echo $line;
?>

Demo

One thought on “Read text file line by line and delete lines using php”
  1. Really helpful article. I learn for many information about in this article. Thanks for sharing this information.

Leave a Reply

Your email address will not be published. Required fields are marked *