How to Export all Products to a CSV File Programmatically using a Root Script in Magento 2?

Hello Magento Friends,

Exporting all products from a Magento 2 store to a CSV file is a common requirement for store owners, developers, and data analysts. While Magento provides a built-in export feature from the admin panel, sometimes you need to automate the process or execute it programmatically using a root script.

hyva theme development

Check out the solution for – Magento 2 Export Product CSV File Permission Issue

In this guide, we’ll walk through how to create a PHP script that exports all products to a CSV file in Magento 2.

Steps to Export all Products to a CSV File Programmatically using a Root Script in Magento 2:

Step 1: We need to create the “exportproduct.php” file in the Magento root directory and add the code given below.

<?php

use Magento\Framework\App\Bootstrap;
use Magento\Framework\App\Filesystem\DirectoryList;

try{
        require __DIR__ . '/app/bootstrap.php';
}catch (\Exception $e){
	echo 'Autoload error: ' . $e->getMessage();
	exit(1);
}

try{
	$bootstrap = Bootstrap::create(BP, $_SERVER);
	$obj = $bootstrap->getObjectManager();

	$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
	$objectManager->get('Magento\Framework\App\State')->setAreaCode('frontend');
	$fileFactory = $objectManager->get('Magento\Framework\App\Response\Http\FileFactory');
	$csvProcessor = $objectManager->get('Magento\Framework\File\Csv');
	$directoryList = $objectManager->get('Magento\Framework\App\Filesystem\DirectoryList');
	$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
	$collection = $productCollection->addAttributeToSelect('*')->load();

	$content[] = ['id' => __('Product Id'),
	'name' => __('Product Name'),
	'sku' => __('Product Sku'),
	'price' => __('Product Price'),
	'short-description' => __('Short Description'),
	'label' => __('Product Alt Text'),
	'value' => __('Product Image Path'),
	'image-width' => __('Product Image Width'),
	'image-height' => __('Product Image Height'),];

	$fileName = 'product_export.csv'; // Add Your CSV File name
	$filePath = $directoryList->getPath(DirectoryList::MEDIA) . "/" . $fileName;

	foreach ($collection as $product){
	    $productFactory = $objectManager->get('Magento\Catalog\Model\ProductFactory')->create()->load($product->getId());
	    $productImages = $productFactory->getMediaGalleryImages();
	    $label = '';
	    foreach ($productImages as $image) {
		$label = $image->getLabel();
	    }
	    
	    list($width, $height, $type, $attr) = getimagesize("pub/media/catalog/product/".$product->getImage());

	    $content[] = [$product->getId(),$product->getName(),$product->getSku(),
	       $product->getPrice(),
		$product->getShortDescription(),
		$label,
		$product->getImage(),
		$width,
		$height,];
	} 

	$csvProcessor->setEnclosure('"')->setDelimiter(',')->saveData($filePath, $content);
	$fileFactory->create($fileName, ['type' => "filename",
	    'value' => $fileName,
	    'rm' => true,
	    // True => File will be remove from directory after download.
	], DirectoryList::MEDIA, 'text/csv', null);

	echo "Product CSV Exported ";

}catch (\Exception $e){
	echo 'Autoload error: ' . $e->getMessage();
	exit(1);
}
Magento version upgrade

Output:

product export csv

Conclusion:

By following the steps above, you can programmatically export all products from Magento 2 to a CSV file using a simple root script. This method is useful for automation, integrations, and bulk data handling. You can extend this script to include additional attributes, apply filters, or even schedule it as a cron job for periodic exports.

Hire Magento Developer

Need further customization? Let us know in the comments!

Previous Article

Magento 2: How to add Custom Field at Hyvä Checkout

Next Article

80+ Unbelievable Facts and Stats About ChatGPT (2025 Edition)

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨