开发者

php create text file. Linebreaks are wrong

I use php to create a f开发者_StackOverflowile 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.


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


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜