简体   繁体   中英

PHP code to display CSV file with option to remove each line

I was able to put together a code to display a CSV file containing a list of emails (each line is an email address) for a newsletter group. I am struggling adding a "remove" function in front of each of those email addresses in case the email is no longer valid (or the user no longer wants to receive emails). Here is what I have:

function my_magic_function(){

$file = TEMPLATEPATH."/user_list.csv";

if (file_exists($file )) {

    $handle = fopen($file , "r+");

    echo '<p><a href="/wp-content/themes/summer/user_list.csv"> Download the CSV File</a></p>';

    $contents = fread($handle, filesize($file));

    $emails = explode(',',$contents);

    for ($x=0; $x<count($emails) -1; $x++){

        echo $emails[$x]."; (remove)<br />";

    }

    fclose($handle);

}else{

    echo "empty";

}

}

What am I missing? How do I make that "(remove)" delete that specific email address (or line)?

Thanks

Output a delete link:

 echo "<a href=delete.php?mail=$email[x]>delete</a> ";

In that delete script read in the email list in an array again. Use array_search() to find the entry, and then do a simple unset() on the returned key. Afterwards write the file back.

 $emails = str_getcsv(file_get_contents("emails.txt"));

 $del_index = array_search($emails, $_GET["mail"]);
 unset($emails[ $del_index ]);

 file_put_contents("email.txt", join(", ", $emails));

Also look into using foreach instead of a for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM