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:
<?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); } ?>
Example CSV for importing new products:
"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"
That’s it. Likewise you can also Magento 2 add images to product gallery programmatically to as an solution to adding images for each product manually in default in Magento 2.
You can use the above example with necessary changes as per your business requirements.
Do share the solution with Magento community via social media.
Thank you.
Continue Reading: