我正在尝试创建一个 zip 文件,其中包含一个简单的文本文件。不幸的是,当我打开 zip 文件时,该文件是空的,尽管我在文本文件中添加了代码。
我已经寻找了有关该主题的其他问题但无济于事,我尝试添加不同的文件,例如照片,但 zip 始终为空。
如何成功地将文件添加到我的 zip 文件中?
这是注释代码
if($_POST['down']){
ob_clean(); //clean and flush
ob_end_flush();
$zip = new ZipArchive(); //create new zip
$filename = 'images.zip'; //call the zip a name
if($zip->open($filename, ZipArchive::CREATE) == FALSE){ //if zip can't be opened or created, kill the script
die('nozip');
}
$string = 'wef2emfofp32fo2mfomepofm'; // a string
$zip->addFromString('text.txt', $string); //add the string to the zip
$zip->close(); //close zip
header("Content-Disposition: attachment; filename=".basename(str_replace(' ', '_', $filename)));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/zip");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($filename));
//download the zip
}
答案 0 :(得分:0)
删除这些代码
if($zip->open($filename, ZipArchive::CREATE) == FALSE){ //if zip can't be opened or created, kill the script
die('nozip');
}
并用 try catch 块包围其他所有内容。如果该块本身不是原因,您可能会在异常消息中找到答案。
答案 1 :(得分:0)
With this simple code (from php documentaion)
I have created succesfully the zip and the content
<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('test.txt', 'file content goes here');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>