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

时间:2012-09-21 11:42:52

标签: php

我想在压缩此文件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文件和保存文件仍然没有成功。 你能帮助我吗?感谢。

1 个答案:

答案 0 :(得分: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