繁体   English   中英

PHP从2个字符串变量中创建一个zip文件

[英]PHP make a zip file from 2 string variables

所以我要做的是拿2个字符串并创建2个文件。 然后从这些文件中创建一个zip文件,让用户下载它们。

这是我有的:

$string1 = 'Some data some data some data';
$string2 = 'Some data some data some data';


$zip = new ZipArchive();
$filename = "test.zip";

if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
   exit("cannot open <$filename>\n");
}


$zip->addFromString("string1.txt", $string1);
$zip->addFromString("string2.txt", $string2);
$zip->close();

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize('test.zip'));

到目前为止没有运气。 任何帮助表示赞赏。

你错过了最重要的部分 - 输出文件! :)

加:

readfile('test.zip');

到php文件的末尾。


此外,HTTP内容长度标头的计算是错误的:

header("Content-Length: ".filesize($zip));

这将使您始终为0(或false),因为filesize期望文件名作为其参数。

将行更改为:

header("Content-Length: ".filesize('test.zip'));

执行这两个操作后,zip将成功下载并包含两个文件。 对于completenes,这里有完整的工作示例:

$string1 = 'Some data some data some data';
$string2 = 'Some data some data some data';


$zip = new ZipArchive();
$filename = "test.zip";

if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
   exit("cannot open <$filename>\n");
}


$zip->addFromString("string1.txt", $string1);
$zip->addFromString("string2.txt", $string1);
$zip->close();

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
// make sure the file size isn't cached
clearstatcache();
header("Content-Length: ".filesize('test.zip'));
// output the file
readfile('test.zip');

您有PHP错误(您可能没有打开错误报告或错误级别足够高)。

filesize()函数接受一个字符串而不是一个对象。 filesize($ filename)将起作用。

打开错误报告:

使用error_reporting(E_ALL | E_STRICT); ini_set('display_errors',1);

或者在php.ini中执行此操作

在所有那些header()调用之后,我想你想要:

readfile($filename); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM