Search code examples
phpsymfonyzip

How to convert a file to zip in php


I have to convert a file rendered in php to zip file.

Here is my code :

 $cacheContent = $gRender->getRenderRaw(
                    "feed-google", array(
                    "_context_" => $this->getType(),
                    "_lang_" => $this->getLang()->getId(),
                    "_id_" => $id));


                $cacheDriver->save($cacheKey, $cacheContent, $cacheExpire);

Can you help me how to convert cacheContent to zip ?

EDITED: In cache folder is genereted a hashfile formated like this : 5d.doctrinecache.data

the file name change everytime is generated. This file inside is looked like this :

    <?xml version="1.0"?>
    <rss version="2.0"  xmlns:g="http://google.com">
                <channel>
                                <title>Item</title>
                    <link></link>
                    <description></description>
                    <language></language>
                    <lastBuildDate></lastBuildDate>
                    <generator></generator>

                <item>
  </item>    
        </channel>
    </rss>

This file i want to convert in zip


Solution

  • try this:

    $rootPath = $_SERVER['DOCUMENT_ROOT'];
    $backup_name = "exported_zip_file.zip";
    $file_name   = "cacheContent.xml";
    $file_content = "cacheContent"; // your string
    $zip = new ZipArchive();
    $zip -> open($rootPath . "/" . $backup_name, ZipArchive::CREATE | ZipArchive::OVERWRITE);
    $zip -> addFromString($file_name, $file_content);
    $zip -> close();
    
    /* this can be deleted */
    
    $zip_final = $rootPath . "/" .$backup_name;
    //
    header("Content-Type: application/zip");
    header("Content-Disposition: attachment; filename = ".$backup_name);
    header("Content-Length: " . filesize($zip_final));
    //
    if(readfile($zip_final)) {
        exit;
    }
    

    Basically you are defining the name of your zip in $backup_name.

    Next you are defining the name of your file in $file_name.

    Next you are defining the content from your file in $file_content.

    Next you are creating or overwriting a new zip archive.

    Next you are creating a new file and adding your $file_content to it.

    And finally closing the zip file.

    Above the "this can be deleted" are some headers to allow your browser to download your new .zip file