Reputation: 1657
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?
Upvotes: 2
Views: 1744
Reputation: 1657
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>
...
Upvotes: 0
Reputation: 39
Try this:
$content = $_POST['content'];
file_put_contents("file.txt", $content);
echo "<pre>";
echo $content;
echo "</pre>";
Upvotes: 0
Reputation: 7843
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?
Upvotes: 0
Reputation: 195
Use php function nl2br()
when displaying content to browser.
<?php echo nl2br($content); ?>
nl2br — Inserts HTML line breaks before all newlines in a string
Upvotes: 2