How To Import Product Data Programmatically In Magento 2
The post is all about getting the Magento 2 product data.
Import product data in the CSV format and then it can be used to implement any product-based feature. For example, the products with a price higher than a certain amount can be shipped with free delivery, or a product from a certain category includes a gift coupon, etc.
Import product data programmatically in Magento 2 store and use it to make your store feature-rich, to earn maximum profit, or to boost your marketing approach!
Steps to import product data programmatically in Magento 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
<?php $file = fopen('var/import/new.csv', 'r', '"'); // set path to the CSV file if ($file !== false) { require __DIR__ . '/app/bootstrap.php'; $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $state = $objectManager->get('Magento\Framework\App\State'); $state->setAreaCode('adminhtml'); // used for updating product stock - and it's important that it's inside the while loop $stockRegistry = $objectManager->get('Magento\CatalogInventory\Api\StockRegistryInterface'); // add logging capability $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/import-new.log'); $logger = new \Zend\Log\Logger(); $logger->addWriter($writer); $header = fgetcsv($file); // get data headers and skip 1st row // enter the min number of data fields you require that the new product will have (only if you want to standardize the import) $required_data_fields = 3; while ( $row = fgetcsv($file, 3000, ",") ) { $data_count = count($row); if ($data_count < 1) { continue; } // used for setting the new product data $product = $objectManager->create('Magento\Catalog\Model\Product'); $data = array(); $data = array_combine($header, $row); $sku = $data['sku']; if ($data_count < $required_data_fields) { $logger->info("Skipping product sku " . $sku . ", not all required fields are present to create the product."); continue; } $name = $data['name']; $description = $data['description']; $shortDescription = $data['short_description']; $qty = trim($data['qty']); $price = trim($data['price']); try { $product->setTypeId('simple') // type of product you're importing ->setStatus(1) // 1 = enabled ->setAttributeSetId(4) // In Magento 2.2 attribute set id 4 is the Default attribute set (this may vary in other versions) ->setName($name) ->setSku($sku) ->setPrice($price) ->setTaxClassId(0) // 0 = None ->setCategoryIds(array(2, 3)) // array of category IDs, 2 = Default Category ->setDescription($description) ->setShortDescription($shortDescription) ->setUrlKey($url_key) // you don't need to set it, because Magento does this by default, but you can if you need to ->setWebsiteIds(array(1)) // Default Website ID ->setStoreId(0) // Default store ID ->setVisibility(4) // 4 = Catalog & Search ->save(); } catch (\Exception $e) { $logger->info('Error importing product sku: '.$sku.'. '.$e->getMessage()); continue; } try { $stockItem = $stockRegistry->getStockItemBySku($sku); if ($stockItem->getQty() != $qty) { $stockItem->setQty($qty); if ($qty > 0) { $stockItem->setIsInStock(1); } $stockRegistry->updateStockItemBySku($sku, $stockItem); } } catch (\Exception $e) { $logger->info('Error importing stock for product sku: '.$sku.'. '.$e->getMessage()); continue; } unset($product); } fclose($file); } ?> |
1 2 3 |
"sku","name","description","short_description","price","qty" "test-sku1","Test product name1","Test product description1","Test product short description1","100","20" "test-sku2","Test product name2","Test product description2","Test product short description2","10","30" |
You can use the above example with necessary changes as per your business requirements.
Any doubts in the implementation can be mentioned in the Comments section below. I’d be happy to help you out.
Do share the solution with Magento community via social media.
Thank you.
Continue Reading:
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.
22 Comments
How about category association
Hii Santosh,
assign categories code is included in above code
->setCategoryIds(array(2, 3))
Thank You.
Hi Sanjay , thanks for the great article
Is the script compatible with Magento 2.4.2 ?
If yes how many products can I import ?
Thabks
Hello Jeff,
Yes, the script is compatible with Magento 2.4.2.(not sure about salable quantity)
Regarding your query about import, the number of product import depends on server timeout
Thank You
Hello Sanjay, I hope you are well.
First of all, I want to thank you for this great work!.
It seems me that you vcan only add a new item but not only update a qt or a price.
What i can do to do it?
thank you
Cheers
Robert
Hello Roberto,
First of all, thank you for the appreciation!
Regarding your question, there’s a setting for import in the admin.
You can do so from there.
Thank You.
Hello Sanjay, I hope you are well.
First, I wanted to thank you for this excellent work and service that you provide us.
Second, I wanted to ask you why when I import products with your code, they are not indexed.
Pdt: I am Colombian, sorry if you do not understand my translation.
Hello,
Thanks for the appreciation!
Regarding your question, The product is added programmatically through CSV and the indexing may set schedule-wise.
Thank You once again.
Hello again Sanjay and thankyou again.
I just implemented it with ease in 2.2.11
I also followed your post to add programmatically images, well done!
Now you should complete the series 🙂
How to upload images for a product.
Have a nice day
Hello,
Please refer to https://meetanshi.com/blog/add-images-to-product-gallery-in-magento-2/
You can change url ($url = $importDir . $product->getImage(); ) as per your image path directory.
I hope it helps.
Thank you for script, I’m just looking at it now.
Before try it I have just a couple of questions
I’m working on version 2.2.11 is it compatible ?
Related field as category id and taxes must already exists ?
Or can I update them later ?
Do you have any indication to import that items.
Can also run it programmatically ?
Thanks for your help
Hello,
Yes, it will work in version 2.2.11
You can create the product and for tax, pass the ID in setTaxClassId()
It won’t be assigned to category. You’ll have to do it manually or customize the code. You can refer to https://meetanshi.com/blog/programmatically-assign-products-to-multiple-categories-in-magento-2/
You can run it programmatically and also update the product afterwards.
Thank you.
Thank you, Sanjay for your article. actually I was looking for a solution for my self and found your article on google. it’s great.
Thanks!
Hi Sanjay,
I want to fetch product data and export them . can you please help me out.? that would be helpful for me.
Hello,
The above post is to import data from CSV. The solution that you want needs customization.
Thanks.
How to use this code in custom module. Will you please help me with this @Sanjay or if i want to use for by backend means admin side.
Hello Pritesh,
I have posted the solution using the root script. If you want to do it using a block or controller, you can simply create an object.
Thank you.
Great tutorial Sanjay bhai!
What about saving images upload during bulk import can you also explain that?
Hello Susheel,
Thanks for the appreciation.
To save images upload during bulk import, check this:
Add ‘image’ in CSV and pass value of imageName .
For example: demo.csv
"sku","name","description","short_description","price","qty","image" "test-sku1","Test product name1","Test product description1","Test product short description1","100","20","img_1.jpg" $img = DomainUrl . '/pub/media/catalog/product'; //This is the directory path from where you have to take the images$url = $img . $data['image'];$product->addImageToMediaGallery($url, array('image', 'small_image', 'thumbnail'), true, false);
You can refer the solution at How To Programmatically Add Images to Product Gallery in Magento 2
Thank you.
Thank you so much Sanjay Bhai!
You are one of the best mentor!
Thank you very much for such appreciative words. It means a lot!