Search code examples
phplaravelphp-ziparchive

cannot add xml file to zip laravel


I want to create a zip folder that includes an xml file and download it. I can download zip but it is empty.

I can create xml and zip :

enter image description here

By the way, $result is the result of ArrayToXml::convert(array,....)

        $zip = new ZipArchive;
   
        $fileName = 'example-'.time().'.xml';
        $zipName = 'example'.time().'.zip';

        if ($zip->open(public_path("storage/zips/".$zipName), ZipArchive::CREATE) === TRUE)
        {
            Storage::disk('public')->put('/files/'.$fileName, $result);        
            $zip->addFile(public_path("storage/files/".$fileName), $result);
            Storage::disk('public')->put('/zips/'.$zipName, $zip);       
          
            $zip->close();           
        }
        return response()->download(storage_path('app\public\zips\\'.$zipName));

How to add xml file to zip. I am new to laravel please help


Solution

  • Have a look at the Madzipper package. Makes working with zip files very easy.

    You can create a zipfile as follows:

    $fileName = 'example-'.time() . '.xml';
    $zip = 'public/zips/example' . time() . '.zip';
    
    Madzipper::make($zip)->addString($fileName, $result)->close();
    

    And then return the path to $zip when downloading the file.

    Please have a look at the docs for more info.