0

I am trying to add a new line to a text file in php

I current have the following line of code

file_put_contents($_SESSION["name"].'.txt', $_POST["item"]."\n", FILE_APPEND);

The goal of this line is to add a new file to a text file associated with a user. It works fine. However I need the text to display on separate lines

I want the text file to look like this

item1
item2
item3
etc..

right now it looks like item1item2item3etc...

how do I get the new line to show up in the text file?

8
  • If you're viewing this file in a browser, you're not seeing those newlines because HTML ignores them. Commented Nov 22, 2013 at 23:05
  • Yes, view the source of the page. How do you want to display them? Commented Nov 22, 2013 at 23:06
  • I am not I am viewing them in a plain text file. I am running this on my local machine. I am not going to ever make it public so I am just saving some amounts of data to text files Commented Nov 22, 2013 at 23:06
  • I just did it and I have 5 lines of text. So it may be your text editor that is not reading it right. Commented Nov 22, 2013 at 23:07
  • Try to use PHP_EOL instead of \n. This is cross-platform. Commented Nov 22, 2013 at 23:08

2 Answers 2

1

Try using \r\n instead otherwise the line breaks will not show in some systems / apps.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, \r is an escape character so will be fine.
1
<?php
file_put_contents("test.txt", "item".PHP_EOL, FILE_APPEND);
file_put_contents("test.txt", "item".PHP_EOL, FILE_APPEND);
file_put_contents("test.txt", "item".PHP_EOL, FILE_APPEND);
?>

Output test.txt:

item
item
item

PHP_EOL is cross platform and will work on Linux/Windows (does not matter where you run the code).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.