Magento Tutorials

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!

Click to rate this post!
[Total: 9 Average: 3.7]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

13 hours ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

4 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

6 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

6 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

7 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

1 week ago