Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need to add data on a new line of a text file 1

Status
Not open for further replies.

999Dom999

Technical User
Apr 25, 2002
266
GB
I have a simple form to sign up for a newsletter, all I want to do is amend a text file with a new email address on the next line, I found some code in a previous post it works fine for the first 3 entries then for some reason I get a blank entry in the $rows array then this gets added again and again with new entries so I end up with a text file with loads of blanks rows, any ideas where its going wrong??

Code:
<?
$file="news.txt"; 

  $rows = file($file);  //read the file into an array

	array_push($rows, $_POST['email']);


    $contents=implode("\n", $rows);  //turn the array back into one long string... depending on OS \n may need some tweaking

    $fh = fopen($file, 'w');  //open the file in a truncated mode
    fwrite($fh, $contents);  //write the contents out
    fclose($fh);  //always close your file handles!
  
echo "Thanks your details have been submitted";


?>
 
file() retains the line endings. so i'd recommend something like this instead:
Code:
array_push($rows, $_POST['email'] ."\n");
$contents=implode("", $rows);
or even better (no need to do a roll-in)
Code:
$email = trim($_POST['email']) . "\n";
$fh = fopen($file, 'abt');
fwrite($fh, $email);
fclose($fh);  
echo "Thanks your details have been submitted";
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top