Sherwin Flight
Sherwin Flight

Reputation: 2363

Extra line breaks in output to file

I am trying to save the content of a textarea to a text file, but am having some trouble with extra line breaks being inserted.

As an example, let's say I enter this into the textarea:

dsfgsdfgdsfgdsg
line2
dsfgdfgdfg
line4

The PHP code that writes this to the text file is:

$content = $_POST['accountMappings'];
$file = "../userlist.txt";
$Saved_File = fopen($file, 'w');
fwrite($Saved_File, $content);
fclose($Saved_File);

The text gets written to the text file, but it gets written like this:

dsfgsdfgdsfgdsg

line2

dsfgdfgdfg

line4

There is an extra line break after each line.

There is nothing else manipulating the code before being saved by the code you see above. Where are these extra blank lines coming from?

Upvotes: 2

Views: 1390

Answers (2)

angelcool.net
angelcool.net

Reputation: 2546

Try this before writing it to the file:

$content = preg_replace('#\r\n?#', "\n", $content);

Upvotes: 3

Ashish Choudhary
Ashish Choudhary

Reputation: 2034

The problem lies with line endings. You must use the solution provided by @angelcool.net which is $content = preg_replace('#\r\n?#', "\n", $content);

Upvotes: 1

Related Questions