如何在 zip 文件之后创建文件 csv 并将文件 zip 保存在服务器上


我想在压缩此文件 csv

并将文件 zip 保存在服务器上后创建一个文件 csv。我编码为:

 foreach($list as $item)
        { 
            $csv .= join("t", $item)."rn"; 
        }  
        $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 文件和保存文件仍未成功。你可以帮我吗?谢谢。

不成功,因为$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

最新更新