首页 > 解决方案 > 使用 php 创建、编写和下载 txt 文件

问题描述

$file = fopen("test.txt", "w") or die("Unable to open file!");
fwrite($file, "lorem ipsum");
fclose($file);

header("Content-Disposition: attachment; filename=\"" . basename($file) . "\"");
header("Content-Type: application/force-download");
header("Content-Length: " . filesize($file));
header("Connection: close");

文件已创建/打开并写入,但未下载。

有什么帮助吗?

标签: php

解决方案


正确的做法是:

<?php

$file = "test.txt";
$txt = fopen($file, "w") or die("Unable to open file!");
fwrite($txt, "lorem ipsum");
fclose($txt);

header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
header("Content-Type: text/plain");
readfile($file);

?>

推荐阅读