基本原理(缓冲区内的字符串内容输出为 txt 文件):header('Content-Disposition: attachment; filename="hoge.txt"');
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.strlen($buf));
print $buf;
文件下载方法如下:header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($filepath));
readfile($filepath);
可以使用 PEAR::File_Archive 的环境,推荐使用以下方法。
优点:
header 之类的东西不用自己写。
可通过改变 toArchive() 的第一个参数可实现压缩之后再下载。
(支持 tar, gz, tgz, bz2, tbz, zip, gzip, ar, deb 等格式)
将缓冲区的内容以文件 a.txt 进行下载。
require_once 'File/Archive.php';
$fa = new File_Archive();
$fa->extract($fa->readMemory($buf, 'a.txt'), $fa->toOutput());
以 zip 格式下载文件。
require_once 'File/Archive.php';
File_Archive::setOption("zipCompressionLevel", 9);
$fa = new File_Archive();
$fa->extract($filepath, $fa->toArchive("hoge.zip", $fa->toOutput()));
多个文件合并压缩之后再下载。
require_once 'File/Archive.php';
$fa = new File_Archive();
$src = $fa->readMulti();
$src->addSource(File_Archive::read("huge1.txt", "hoge/huge1.txt"));
$src->addSource(File_Archive::read("huge2.txt", "hoge/huge2.txt"));
$src->addSource(File_Archive::read("huge3.txt", "hoge/huge3.txt"));
$fa->extract($src, $fa->toArchive("hoge.zip", $fa->toOutput()));
extract() 的第一个参数是输入方法,第二个参数是输出方法。
稍微修改以上例子即可实现各种组合形式的下载。
除了下载用的 toOutput(),还有 toFile(),toMail(),toVariable() 等方法,因此具有很广的应用范围。
以上内容翻译整理自
PHPでファイルダウンロードさせる方法