0

phpスクリプトのユーザーがサーバーから特定のテキストファイルのコンテンツをダウンロードできるようにしたいのですが、サーバーから直接ダウンロードしたくないので、download.phpというphpファイルを調べたいと思います。

このコードを使用してファイルプロンプトをトリガーします

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

コードは機能し、ファイルはダウンロードされますが、コードはそのテキストファイルの新しい行を無視しているようです。

元のテキストファイルの内容が

word1
word2
word3
word4
word5

ダウンロードしたファイルの内容は次のようになります

word1word2word3word4word5

ダウンロードしたファイルが実際に元のテキストファイルの新しい行を保持するように修正するにはどうすればよいですか?

4

1 に答える 1

2

これは、テキストファイルのEOLをLinux、Windows、およびMacからWindowsに変換するためのコードです。したがって、ファイルのEOLが何であっても、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("\r\n", "\n", $f); //Convert Windows to Unix
$f = str_replace("\r", "\n", $f); //Convert Mac to Unix
$f = str_replace("\n", "\r\n", $f); //Convert Unix to Windows
echo $f;

コードは短いですが、巨大なファイルにはあま​​り適していません。

于 2012-05-19T14:57:02.660 に答える