Writing new line in text file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
skallagrimur
Forum Newbie
Posts: 9
Joined: Fri Nov 12, 2010 4:33 am

Writing new line in text file

Post 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
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Writing new line in text file

Post 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);
skallagrimur
Forum Newbie
Posts: 9
Joined: Fri Nov 12, 2010 4:33 am

Re: Writing new line in text file

Post by skallagrimur »

Thanks for the fast response. I will try this.
skallagrimur
Forum Newbie
Posts: 9
Joined: Fri Nov 12, 2010 4:33 am

Re: Writing new line in text file

Post 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?
skallagrimur
Forum Newbie
Posts: 9
Joined: Fri Nov 12, 2010 4:33 am

Re: Writing new line in text file

Post by skallagrimur »

I figured it out, add \r\n behind $string:

Code: Select all

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