【问题标题】:php create text file. Linebreaks are wrongphp 创建文本文件。换行是错误的
【发布时间】:2011-08-26 09:19:57
【问题描述】:

我用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"

所以。我究竟做错了什么?在 header 之前输出一些东西,所以 header 不起作用?

更新:感谢您的帮助。两个正确答案同时出现。订购“最旧的优先”时的第一个答案被标记为正确答案。使用单引号解决了这个问题。

输出开头的两个空格的问题与给出的示例中的 code/php 无关。它是来自所使用框架的工件。

【问题讨论】:

    标签: php file text download line-breaks


    【解决方案1】:

    换行符(使用\n & \r)只能在双引号中识别,而不是在单引号中。

    【讨论】:

      【解决方案2】:

      改用双引号,单引号不能识别换行

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

      【讨论】:

      • 谢谢。发现。新我需要找到该行开头的两个中断的来源。
      • 您在某些地方使用\n\r,这可能会导致双换行符,具体取决于操作系统。
      • 双引号。这就是我最后 45 分钟的时间。双引号。谢谢你。多么简单的细节却大不相同。
      猜你喜欢
      • 2012-08-07
      • 1970-01-01
      • 2013-11-17
      • 1970-01-01
      • 1970-01-01
      • 2013-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多