2

我想在压缩这个文件 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 文件和保存文件仍未成功。你能帮助我吗?谢谢。

4

1 回答 1

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
于 2012-09-21T12:02:04.617 回答