How to Create Zip File in Magento 2
A ZIP file is a format that can be used to compress one or more files together at the same location. It helps in reducing the file size and makes it easy to share or transfer the files.
Also, as the data is encrypted in the zip file, the data security is maintained. Whenever you want to send a large batch of files via Email or any other medium, you can overcome the limitation of file size by using a zip file.
Keeping in mind these uses of zip files, I came up with a method to create zip file in Magento 2.
The admin can use the below solutions in various cases like when a customer uploads multiple files from the frontend in case of product customization or personalization. The admin or store designer will have to access these files to implement the personalization that the customer has asked for. In this case, instead of transferring multiple files one by one, the admin can create Magento 2 zip file.
Check the below solution for the same.
Method to create zip file in Magento 2:
You can use any of the below code to create a zip file in Magento 2 as shown below:
1 2 3 4 5 6 7 8 |
public function getZip($source,$destination) { $zip = new \ZipArchive(); $zip->open($destination, \ZipArchive::CREATE); $zip->addFile($source, basename($source)); $zip->close(); return $destination; } |
Next, you can call the following function in .phtml file to create a zip file in Magento 2.
getZip('D:\My Folder\download.jpg','D:\zip\Meetanshi.zip')
OR
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php namespace Vendor\Module\Block; use Magento\Framework\Archive\Zip; protected $zip; public function __construct(Context $context,Zip $zip) { $this->zip = $zip; parent::__construct($context); } public function getZip() { $this->zip->pack('D:\My Folder\download.jpg','D:\zip\Meetanshi.zip'); } |
That’s it.
Any doubts? Do mention them in the Comments section below. I’d be happy to help you out.
Also, do share the solution with the Magento Community via social media.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
How to Use SQL Query for Case Sensitive Data in Magento 2
10 Best CRM Software Tools (+ Tips to Pick The Right One)
Next