php 创建文本文件。换行符错误
我使用 php 创建一个文件,按下链接即可下载。
已经尝试了多种代码变体。没有理由这个不应该工作:
$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;
但是返回的文件以我没有插入的两个空格开头。 \r\n 上没有换行符。
如果我在记事本++中打开文件,我会在“输入”处看到换行符 在普通记事本中,甚至不存在中断。下载的文本文件中的输出在引号之间如下所示:
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。我做错了什么?在标头之前输出一些内容,因此标头不起作用?
更新:感谢您的帮助。两个正确答案同时出现。当订购“最旧的优先”时,第一个答案被标记为正确答案。使用单引号解决了这个问题。
输出开头的两个空格的问题与给定示例中的 code/php 无关。它是所使用框架的工件。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
换行符(使用
\n
和\r
)只能在双引号中识别,不能在单引号中识别。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
so it will look like