View Full Version : fwrite() - Content on New Lines

07-29-2007, 09:38 PM
I am following a tutorial teaching me about the multiple read/right operations.

the code below works fine in that when i submit text into the form my textfile will update. the problem is that the updat is not on a new line, it is simply shown beside the old text.

the tutorial said to add "\n" (as i did in my code below) however this is not working form me :(

// open the file in append mode
$file = fopen($_SERVER['DOCUMENT_ROOT'].'/update/filetest05.txt', 'a');
// write the contents after inserting new line
fwrite($file, "\n$contents");
// close the file

any help would be great.

07-29-2007, 10:01 PM
On windows XP this works fine. Maybe you are using Mac, or Linux, i know that there could be different way to go to new line on those OS's.

As for something else too you could check

A list of possible modes for fopen() (http://www.php.net/fopen), that is that 'a' you are using in fopen. And you could maybe use other more convenient way.

In your function instead of first setting \n$content, i would set $content\n beacouse 'a' mode

Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

So if it's first time your writing to file it will create empty line on the begining of the file, and new lines at the end of the $content, so you will have empty line at the begining of the file...

07-30-2007, 03:31 AM
it depends on which application you use to view the file, notepad for example requires "\r\n" but many editors autodetect the newline type and will display the newline regardless.

e.g. on windows I find I have to use "\r\n" if I want say notepad to display the newline whilst all linux editors seem happy with "\n".

07-30-2007, 05:23 AM
im viewing the output on a linux server so the book said to only use "\n". It also said to put the \n infront.
regradless i had already tryed all possible variotions and none worked.

07-30-2007, 05:28 AM
Wait, you are saying after you echo the new text file its not correctly formatted or are you saying its not correctly formatted when viewing the text file?

If you are saying that after echoing its not correctly formatted then this normal. New lines mean nothing in HTML, you need to use the nl2br function to maintain the new line characters.

07-30-2007, 06:17 AM
New lines mean nothing in HTML, you need to use the nl2br function to maintain the new line characters.

YES! If you are viewing it in a browser, you will not see new lines there like aerospace said.

Open your text file in some editor, or do a view source! If there is nothing in your text file, than probably your path is invalid.