Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php create text file. Linebreaks are wrong

I use php to create a file that can be donwloaded when pressing a link.

Many variations of code has been tried. No reason this one should not work:

$output = 'test    spaces, test 
enter, test n, \ntest nr, \n\rtest nt, \n\ttest html-br, <br /><br>end of line';
$output .= '\r\n';
$output .= 'blahblah';
header('Content-type: text/plain');
header('Content-Disposition: attachment;filename="'.$filename.'.txt"');
print $output;
exit;

But the file that is returned starts with two spaces that I did not insert. No linebreaks on \r\n.

If I open the file in notepad++ I do get a linebreak on the 'enter' In ordinary notepad that break is not even there. Output in downloaded text file is like this between quotes:

  In notepad++
  "  test    spaces, test 
  enter, test n, \ntest nr, \n\rtest nt, \n\ttest html-br, <br /><br>end of line\r\nblahblah"

So. What am I doing wrong? Outputting something before the header, so the header is not working?

UPDATE: Thanks for the help. Two right answer at the exact same time. First answer when ordered "oldest first" got marked as right answer. Using single quotes solved the issue.

The issue with the two empty spaces in the beginning of the output is not related to the code/php in the example given. It is an artifact from the framework that is used.

like image 438
Tillebeck Avatar asked Jun 03 '26 00:06

Tillebeck


2 Answers

Newlines (using \n & \r) are only recognized in double quotes, not in single quotes.

like image 56
gnur Avatar answered Jun 05 '26 15:06

gnur


Use double quotes instead, single quotes doesn't recognize new lines

// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';

// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';

so it will look like

$output = "test    spaces, test 
enter, test n, \ntest nr, \n\rtest nt, \n\ttest html-br, <br /><br>end of line";
$output .= "\r\n";
$output .= 'blahblah';
header('Content-type: text/plain');
header('Content-Disposition: attachment;filename="'.$filename.'.txt"');
print $output;
exit;
like image 32
genesis Avatar answered Jun 05 '26 13:06

genesis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!