user2555499
user2555499

Reputation: 3

How do I write on a file without clean it?

How do I write on a file without clean the file using fwrite function? I would like to write skiping a line using fwrite in a text file.

$fp = fopen('somefile.txt', 'w');
 fwrite($fp, "Some text");
  fwrite($fp,"More texto in another line");
 fclose($fp);

Upvotes: 0

Views: 468

Answers (2)

Kevin Ji
Kevin Ji

Reputation: 10489

Set your open mode to "append" instead of "write" (see the documentation for fopen):

$fp = fopen('somefile.txt', 'a');

If you are on Windows, you may want to consider using the t flag to denote the file you are opening as a text file, so that the proper line-ending character is being used (\r\n instead of just \n for Windows):

$fp = fopen('somefile.txt', 'at');

Now, to add your text onto new lines, make sure to use PHP_EOL for the newline character character to ensure that the right newline characters are being written for the right OSs:

fwrite($fp, PHP_EOL . 'Some text');
fwrite($fp, PHP_EOL . 'More text on another line');

Upvotes: 2

bidon
bidon

Reputation: 3

Try to change mode in fopen function from 'w' to 'a'

 $fp = fopen('somefile.txt','a');

Upvotes: 0

Related Questions