This post is all about the import product data in Magento 2.
Import product data in CSV format to enable various product-based features. For example, products priced above a certain amount can qualify for free delivery, or items from a specific category can include a gift coupon. These functionalities can be effectively managed through the Magento 2 order import feature. let’s see the following steps below:
Step-1 Create a CSV file var/import/new.csv
Example CSV for importing new products:
1 2 3 |
"sku","name","description","short_description","price","qty" "test1","Test product name1","This is first product","Short description1","100","30" "test2","Test product name2","This is second product","Short description2","10","50" |
Step-2 Create a PHP file at the Magento root folder import.php
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 |
<?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(); // log provides debugging information that assists you with understanding when an error occurred or what lead to the error. $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) ->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); } ?> |
You can use the above example with necessary changes as per your professional requirements.
Any doubts in the topic can be mentioned in the Comments section below.
Thank you.