dppxp79175 2019-03-16 19:15
浏览 289

使用php将文件添加到zip并下载zip

I have a web service that is requesting for data. The data received is being stored in the variable $response.

After that, i am creating files to store the data.

Then i am trying to add these files to a zip and afterwards download that zip. I have consulted various questions and answers similar to mine but i still cannot solve my problem. Note that i have the zip library installed.

Below is my php script:

// Load zip library
$zip = new ZipArchive();

//Zip name
$zip_name = "data.zip";

if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){ 
    // Opening zip file to load files
    $error = "ZIP creation failed at this time";
}
else{
    echo "zip creation successful";
}

function myFunc(){
    //Some codes
     global $zip;

     $myfile = fopen($filepath, "w");

     fwrite($myfile, $response);
     fclose($myfile);

     echo "test1";
     try {
        //add file to zip
        $zip->addFile($myfile);
     }
     catch (Exception $e) {
        echo $e->getMessage();
     }
     echo "test2";
}

$zip->close();

//Some codes    

if(file_exists($zip_name)){
    // push to download the zip
    header('Content-type: application/zip');
    header('Content-Disposition: attachment; filename="'.$zip_name.'"');
    readfile($zip_name);

    // remove zip file is exists in temp path
    unlink($zip_name);
}

After running the above script, test1 is being displayed and not test2. I think that the problem lies in this line $zip->addFile($myfile);.

From previous posts, i could notice that the function addFile takes 2 parameters. How can i edit my code for this?

Thanks for your help.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 wireshark抓不到vlan
    • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
    • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
    • ¥15 stata安慰剂检验作图但是真实值不出现在图上
    • ¥15 c程序不知道为什么得不到结果
    • ¥40 复杂的限制性的商函数处理
    • ¥15 程序不包含适用于入口点的静态Main方法
    • ¥15 素材场景中光线烘焙后灯光失效
    • ¥15 请教一下各位,为什么我这个没有实现模拟点击
    • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来