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?

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; 
}
  • 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 Apr 25 '17 at 7:25
  • Sorry, was due to typo error... working well. answer apporved – Alexglvr Apr 25 '17 at 7:48
8

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

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, privacy policy and cookie policy

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