问题:
当我下载一个应该包含csv文件的zip存档时,我会得到一个空存档或无效存档。现在,我可以在服务器上使用csv制作zip存档,然后通过FileZilla下载。这不是理想的用例。用户想要在单击按钮后自动下载。
关于计划:
代理商注册活动(即向其发送RSVP)并提供一组照片。
每位代理商都有+1张照片。用户想要为每个事件(即注册数据)下载所有RSVP的列表。对于每个RSVP,用户还希望看到他们上传到服务器的照片。
计划目标:
计划的现状:
已创建CSV文件。下面它被添加到ZipArchive对象。下载了zip文件,发现它为空。
//store the result of the query. Included to show process
$result = mysqli_query($dbh, $sql);
//open the file to write the information to.
$file = fopen('event-report.csv', 'w');
$txt .= 'Title Company,' .'Event ID,' . 'Event Time,' . 'First Name,' . 'Last Name,' . 'Email,' . 'Agent Company,' . 'Phone Number,' . 'Listing ID,' . 'URL,' . 'Address,' . 'ZIP,' . "\n";
while ($row = mysqli_fetch_row($result)){
for ($i=0; $i<12; $i++){
$txt .= $row[$i] . ','; //About the agent attending
}
$txt .= "\n";
$listings[$listing_count] = $row[8];
}
fputs($file, $txt); //store into csv file
fclose($file); //verified on server; contains desired output
$zip = new ZipArchive();
$dir = 'tmp'; //create temporary directory with write access
if ( !file_exists($dir) ) {
mkdir ($dir, 0755); //Everything for owner, read/execute for others
}
if($zip->open('test.zip', ZIPARCHIVE::CREATE) === TRUE ){
$zip->addFile('event-report.csv');
if (file_exists($zip->getFromName('event-report.csv'))){
echo "Exists";
}
else{
echo "Does Not Exist";
echo $_SERVER['DOCUMENT_ROOT'];
}
}
else {
echo "Failed code";
}
$zip->close();
if(!$return){
echo " You do not have write access to current folder.";
}
else{
echo "You do have access."; //without headers, the zip containing csv successfully created on server.
}
header('Content-disposition: attachment; filename=download.zip');
header('Content-type: application/zip');
readfile($dir.'/test.zip'); //When downloaded: still empty/invalid.
可能出现的问题
$zip->addFile('/f1/f2/f3/f.csv');
问题的
答案 0 :(得分:0)
添加到存档时,您需要使用绝对路径显式。
$zip->addFile($abs_path, $relative_path);
答案 1 :(得分:0)
解决方案:在调用readfile()之前刷新头文件。我了解到我不需要flush()但是我还是把它留在了那里。请参阅帮助我包含这两个陈述here
的SO帖子header('Content-type: application/zip');
header('Content-disposition: attachment; filename=test.zip');
ob_clean(); // discard any data in the output buffer (if possible)
flush(); // flush headers (if possible)
readfile('tmp/test.zip');
exit();
我还通过错误检查改变了一些小问题,我想我会在下面提到:
我创建了一个具有某些权限的目录,这些权限将保存我要放入存档的文件。这是在创建csv和zip之前的开头完成的。
$dir = 'tmp/';
if ( !file_exists($dir) ) {
mkdir ($dir, 0777);
}
打开文件也发生了变化。它现在涉及我制作的新目录:
$zip = new ZipArchive;
if($zip->open($dir.'test.zip', ZIPARCHIVE::CREATE) === TRUE ){
$res = $zip->addFile('tmp/event-report.csv', 'event-report.csv'); //add the report csv file.
if ($res){
echo "Exists ";
}
else{
echo "Does Not Exist ";
//echo $_SERVER['DOCUMENT_ROOT'];
}
}
感谢所有贡献或只是看过这个问题的人。