Site icon MageComp Blog

How to Import Product Data Programmatically In Magento 2

Hello Magento Friends,

Today we will learn about How to Import Product Data Programmatically In Magento 2.

An E-commerce store has a large amount of product data. Product Data can be uploaded in CSV format in Magento 2. Then this data can be used to execute product-based features in Magento 2.

For example, free delivery will be offered to a product when the customer order amount is higher. You may also want to give a gift coupon to customers for some product. To accomplish these requirements, you as a store admin need product data.

So here is How to Import Product Data Programmatically In Magento 2

Steps to Import Product Data Programmatically In Magento 2:

Step 1: Create a CSV file at the below path

var/import/product.csv

"sku","name","description","short_description","price","qty"
"product1","Test product1","This is 1 product","Short description 1","100","30"
"product2","Test product2","This is 2 product","Short description 2","10","50"

Step 2: Create a PHP file, Import.php at Magento Root folder 

And add the below code:

<?php
$file = fopen('var/import/product.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');
    $stockRegistry = $objectManager->get('Magento\CatalogInventory\Api\StockRegistryInterface');

    $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/import-product.log');
    $logger = new \Zend\Log\Logger(); 
    $logger->addWriter($writer);

    $header = fgetcsv($file); // get data headers and skip 1st row
    $required_data_fields = 3;

    while ($row = fgetcsv($file, 3000, ",") )
    {
        $data_count = count($row);
        if ($data_count < 1)
        {
            continue;
        }
        $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') // product type
                    ->setStatus(1) // 1 = enabled
                    ->setAttributeSetId(4)
                    ->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);
}	
?>

Conclusion:

Hence, this way you can Import Product Data Programmatically In Magento 2. Facing difficulties with the code? Get in touch with me via the comment box. Share your article with Magento friends and stay connected with us.

Happy Reading!

Exit mobile version