[英]Downloaded zip archive empty after adding csv file
問題:
當我下載應該包含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');
問題
添加到歸檔文件時,您必須使用絕對路徑來明確顯示。
$zip->addFile($abs_path, $relative_path);
解決方案:在調用readfile()之前刷新標頭。 我了解到我不需要flush(),但無論如何我還是把它留在那里。 看到這樣的帖子,它幫助我在此處包括了這兩個聲明
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'];
}
}
感謝所有貢獻者或剛剛看過這個問題的人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.