2012-09-21 75 views
1

我想創建一個文件CSV文件後壓縮此文件CSV和保存文件zip在服務器。 我代碼:如何創建一個文件CSV文件後,CSV文件,並保存在服務器上的zip文件

foreach($list as $item) 
     { 
      $csv .= join("\t", $item)."\r\n"; 
     } 

     $csv = chr(255).chr(254).mb_convert_encoding($csv,"UTF-16LE","UTF-8"); 

     header("Content-type: application/x-msdownload"); 
     header("Content-disposition: csv; filename=CSV_".date("YmdHis").".csv; size=".strlen($csv)); 

     $zip = new ZipArchive(); 
     $zip_name ="CSV_".$dateTimeNow.".zip"; // Zip name 
     if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE) 
     {       
       $error .= "* Sorry ZIP creation failed at this time"; 
     } 
     $zip->addFile($csv); 
     $zip->close(); 

文件CSV創造好的,但zip文件,保存文件仍然沒有sucesssfull。 你能幫我嗎?謝謝。

回答

0

不成功,因爲$zip->addFile期待一個文件,但chr(255).chr(254).mb_convert_encoding($csv,"UTF-16LE","UTF-8")返回

下面是解

$csv = "ABC" ; // Define CSV to avoid notice error 
$csv = chr(255).chr(254).mb_convert_encoding($csv,"UTF-16LE","UTF-8"); 

header("Content-type: application/x-msdownload"); 
header("Content-disposition: csv; filename=CSV_".date("YmdHis").".csv; size=".strlen($csv)); 

$file_name = "abc.csv"; 
file_put_contents($file_name, $csv); // dump csv to temp file 

$zip = new ZipArchive(); 
$zip_name = "CSV.zip" ; // Zip name 
touch($zip_name); 

if ($zip->open($zip_name) === TRUE) { 
    $zip->addFile($file_name); // add the temp file to zip 
    $zip->close(); 
} else { 
    $error .= "* Sorry ZIP creation failed at this time"; 
} 

unlink($file_name); // remove temp csv 
+0

file_put_contents($ FILE_NAME,$ CSV);命令不會創建臨時文件。它顯示下載文件abc.csv.html – mum

+0

@mum我不知道你在哪裏得到'.html'在你的文件末尾.......我跑了代碼,它工作得很好 – Baba

+0

我的代碼: $ filename ='CSV_123.csv「; file_put_contents($ file_name,$ csv);但不保存文件,它顯示對話框保存文件CSV_123.csv。 – mum

相關問題