Page 1 of 1

Writing new line in text file

Posted: Sun Nov 14, 2010 8:07 am
by skallagrimur
Hello. I'm looking for help with writing a new line into a text file.

Say I got:

Code: Select all

$cell1 = "word1";
$cell2 = "word2";
$cell3 = "word3";
textfile.txt, that looks like this:

[text]oldword1|oldword2|oldword3
olderword1|olderword2|olderword3[/text]

Could someone point me to a place, or even show me some code, that would help add a new line into textfile.txt with

[text]$cell1|$cell2|$cell3[/text].

All help is greatly appreciated.
Thank you,
skallagrimur

Re: Writing new line in text file

Posted: Sun Nov 14, 2010 8:25 am
by Celauran
fopen() and fwrite() will do the trick.

Code: Select all

$string = $cell1 . '|' . $cell2 . '|' . $cell3;
$fh = fopen('textfile.txt', 'a+');
fwrite($fh, $string);
fclose($fh);

Re: Writing new line in text file

Posted: Sun Nov 14, 2010 8:36 am
by skallagrimur
Thanks for the fast response. I will try this.

Re: Writing new line in text file

Posted: Sun Nov 14, 2010 8:56 am
by skallagrimur
That works almost perfectly, I've been trying to read the manual but I can't find out what to put instead of "a+" so that it writes into the next line. When it is "a+" it writes at the end of the line. Could you tell me?

Re: Writing new line in text file

Posted: Sun Nov 14, 2010 9:20 am
by skallagrimur
I figured it out, add \r\n behind $string:

Code: Select all

fwrite($fh, "$string\r\n");
Thanks again