doudouxuqh198138 2012-05-19 14:25
浏览 43
已采纳

PHP提示下载忽略新行

I want the users of my php script to be able to download the contents of a certain text file from my server but I don't want them to download it directly from my server so I want to go through a php file called download.php

I use this code to trigger the file prompt

header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=textfile.txt");
header("Content-Length: " . filesize('textfile.txt');

$fp = fopen('textfile.txt', "r");
fpassthru($fp);
fclose($fp);

The code works, the file gets downloaded but it seems the code ignores new lines of that text file.

Let's say the content of the original text file is

word1
word2
word3
word4
word5

The content of the downloaded file would be

word1word2word3word4word5

How can I fix it that the downloaded file actually retains the new lines of the original text file?

  • 写回答

1条回答 默认 最新

  • dounuo7954 2012-05-19 14:57
    关注

    Here's a code to convert text file EOLs from Linux, Windows and Mac to Windows. So no matter what EOLs your file has it will open fine on Win.

    header("Content-Type: text/plain");
    header("Content-Disposition: attachment; filename=textfile.txt");
    header("Content-Length: " . filesize('textfile.txt'));
    
    $f = file_get_contents('textfile.txt');
    $f = str_replace("
    ", "
    ", $f); //Convert Windows to Unix
    $f = str_replace("", "
    ", $f); //Convert Mac to Unix
    $f = str_replace("
    ", "
    ", $f); //Convert Unix to Windows
    echo $f;
    

    The code is short but it's not too good for huge files.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)