2

I have form that uses POST to send information to PHP script. PHP reads $content and saves it to file.txt, and also displays it on browser using the following code:

$content = $_POST['content'];

file_put_contents("file.txt", $content);
echo $content;

If I use line breaks in form, then file.txt contains them all. But when I'm echoing same $content to browser, there are no line breaks at all. And I mean in source code. My purpose is to use $content in another forms <textarea>, but even textarea does not show any line breaks.

How file_put_contents finds the line breaks?

darx
  • 1,417
  • 1
  • 11
  • 25

4 Answers4

2

Use php function nl2br() when displaying content to browser.

<?php echo nl2br($content); ?> 

nl2br — Inserts HTML line breaks before all newlines in a string

http://php.net/manual/en/function.nl2br.php

Community
  • 1
  • 1
Anish
  • 195
  • 6
  • `echo nl2br($content)` does not have any effect. I have also tried to replace "\n" to "
    " with str_replace, but no luck.
    – darx Oct 08 '16 at 18:20
  • @darx I've tested on my end file is displaying line breaks, and browser also displaying line breaks using `nl2br()`. Can you please, show me what's in you `$content`? – Anish Oct 08 '16 at 18:43
0

I think the line breaks are not gone. They are just not visible with Notepad or Windows based editor.

Most browsers use Unix / MacOS line break (\n) only, while Windows editor only recognize Windows linebreak (\r\n).

Instead of

$content = $_POST['content'];

Try to do

$content = str_replace("\n", "\r\n", $_POST['content']);

More reference:

Difference between CR LF, LF and CR line break types?

Community
  • 1
  • 1
Koala Yeung
  • 7,475
  • 3
  • 30
  • 50
  • Thanks for your answer, but replacing "\n" with "\r\n" has no effect. When I open `file.txt` in any editor, it contains all the line breaks. So that's not the problem. Problem is that in web page, I can't get those line breaks. – darx Oct 08 '16 at 18:28
0

Try this:

$content = $_POST['content'];

file_put_contents("file.txt", $content);
echo "<pre>";
echo $content;
echo "</pre>";
orbit
  • 39
  • 1
  • 9
  • Tried. No help. It just seems that POST somehow get rid of all my line breaks, but that's not the case because `file_put_contents` saves all line breaks to text file. – darx Oct 08 '16 at 18:39
  • 1
    Is the $content coming from a textarea or input? – orbit Oct 08 '16 at 18:41
  • It's coming from javascript generated input tag. Input does not support line breaks? But how I can get them in saved file... – darx Oct 08 '16 at 18:47
0

Ok, thanks to Skye, the problem is solved. I used javascript generated <input> tag to send text containing line breaks. I changed it to <textarea> and I can catch all the line breaks now.

I can't still understand why I can have line breaks when saving to file.txt from <input>...

darx
  • 1,417
  • 1
  • 11
  • 25