我使用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。
上没有换行符如果我在记事本++中打开文件,我会在'enter'上获得一个换行符 在普通的记事本中,破坏甚至不存在。下载文本文件中的输出在引号之间是这样的:
In notepad++
" test spaces, test
enter, test n, \ntest nr, \n\rtest nt, \n\ttest html-br, <br /><br>end of line\r\nblahblah"
因此。我究竟做错了什么?在标题之前输出一些东西,所以标题不起作用?
更新:感谢您的帮助。两个正确答案在同一时间。订购“最早的第一个”时的第一个答案被标记为正确答案。使用单引号解决了这个问题。
输出开头的两个空格的问题与给定示例中的代码/ php无关。它是使用的框架中的工件。
答案 0 :(得分:8)
换行符(使用\n
&amp; \r
)仅在双引号中识别,而不是在单引号中识别。
答案 1 :(得分:4)
使用双引号代替,单引号无法识别新行
// 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';
所以它看起来像
$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;