8

I need to be able to treat zip files programmatically.

In magento 1.9 I was doing :

$zip = new ZipArchive();

        if ($zip->open($Zippath) === TRUE) 
        {
            $zip->addFile($Filepath, $Filename);
            $zip->addFile($FilepathL, "toto.txt");
            $zip->close();
            return TRUE;    }

How can I do the same in magento 2?

3 Answers 3

6

You can do this the same way

$zip = new \ZipArchive();

if ($zip->open($Zippath) === TRUE) {
    $zip->addFile($Filepath, $Filename);
    $zip->addFile($Filepath, "toto.txt");
    $zip->close();
    return TRUE; 
}
2
  • I have just tested and get an error on $zip->close(); : Warning: ZipArchive::close(): Read error: Is a directory. For $FilePath i have /foo/bar and $FileName toto.txt
    – Alexglvr
    Commented Apr 25, 2017 at 7:25
  • Sorry, was due to typo error... working well. answer apporved
    – Alexglvr
    Commented Apr 25, 2017 at 7:48
11

Alternativaly you can use the Magento framework class of M2 called Magento\Framework\Archive\Zip and call the pack() method.

For example, if you injected the class and assigned it to the $zipArchive variable you can do:

$this->zipArchive->pack($source, $destination);
3
  • Does this work with AWS S3 Remote Storage. I am getting some errors when unpacking a zip.
    – Harish ST
    Commented Nov 26, 2021 at 9:00
  • The return of \ZipArchive::open() is 9 for me. Which is ZIP_ER_NOENT .
    – Harish ST
    Commented Nov 26, 2021 at 9:31
  • Seems we cannot directly perform operations on zip file inside S3.
    – Harish ST
    Commented Nov 26, 2021 at 9:45
4

Its basically a php class. It has nothing to do with Magento. However you can check the implementation is still like the same.

Here is the class http://php.net/manual/en/class.ziparchive.php

And here is the implementation in Magento2.

If you open

lib\internal\Magento\Framework\Archive\Zip.php you will find this

public function pack($source, $destination)
    {
        $zip = new \ZipArchive();
        $zip->open($destination, \ZipArchive::CREATE);
        $zip->addFile($source);
        $zip->close();
        return $destination;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.