{"id":946,"date":"2020-04-20T05:24:58","date_gmt":"2020-04-20T05:24:58","guid":{"rendered":"https:\/\/meetanshi.com\/blog\/2020\/04\/20\/import-product-data-programmatically-in-magento-2\/"},"modified":"2025-05-22T13:27:43","modified_gmt":"2025-05-22T07:57:43","slug":"import-product-data-programmatically-in-magento-2","status":"publish","type":"post","link":"https:\/\/meetanshi.com\/blog\/import-product-data-programmatically-in-magento-2\/","title":{"rendered":"How To Import Product Data Programmatically In Magento 2"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">The post is all about getting the Magento 2 product data.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Import product data programmatically in Magento 2 store and use it to make your store feature-rich,&nbsp;to earn maximum profit, or to boost your marketing approach!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Steps to import product data programmatically in Magento 2:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\n    \n    $file = fopen('var\/import\/new.csv', 'r', '\"'); \/\/ set path to the CSV file\nif ($file !== false) {\n\n    require __DIR__ . '\/app\/bootstrap.php';\n    $bootstrap = \\Magento\\Framework\\App\\Bootstrap::create(BP, $_SERVER);\n\n    $objectManager = $bootstrap->getObjectManager();\n\n    $state = $objectManager->get('Magento\\Framework\\App\\State');\n    $state->setAreaCode('adminhtml');\n\n    \/\/ used for updating product stock - and it's important that it's inside the while loop\n    $stockRegistry = $objectManager->get('Magento\\CatalogInventory\\Api\\StockRegistryInterface');\n\n    \/\/ add logging capability\n    $writer = new \\Zend\\Log\\Writer\\Stream(BP . '\/var\/log\/import-new.log');\n    $logger = new \\Zend\\Log\\Logger();\n    $logger->addWriter($writer);\n\n    $header = fgetcsv($file); \/\/ get data headers and skip 1st row\n\n    \/\/ enter the min number of data fields you require that the new product will have (only if you want to standardize the import)\n    $required_data_fields = 3;\n\n    while ( $row = fgetcsv($file, 3000, \",\") ) {\n\n        $data_count = count($row);\n        if ($data_count &lt; 1) {\n            continue;\n        }\n\n        \/\/ used for setting the new product data\n        $product = $objectManager->create('Magento\\Catalog\\Model\\Product');         \n        $data = array();\n        $data = array_combine($header, $row);\n\n        $sku = $data['sku'];\n        if ($data_count &lt; $required_data_fields) {\n            $logger->info(\"Skipping product sku \" . $sku . \", not all required fields are present to create the product.\");\n            continue;\n        }\n\n        $name = $data['name'];\n        $description = $data['description'];\n        $shortDescription = $data['short_description'];\n        $qty = trim($data['qty']);\n        $price = trim($data['price']);\n\n        try {\n            $product->setTypeId('simple') \/\/ type of product you're importing\n                    ->setStatus(1) \/\/ 1 = enabled\n                    ->setAttributeSetId(4) \/\/ In Magento 2.2 attribute set id 4 is the Default attribute set (this may vary in other versions)\n                    ->setName($name)\n                    ->setSku($sku)\n                    ->setPrice($price)\n                    ->setTaxClassId(0) \/\/ 0 = None\n                    ->setCategoryIds(array(2, 3)) \/\/ array of category IDs, 2 = Default Category\n                    ->setDescription($description)\n                    ->setShortDescription($shortDescription)\n                    ->setUrlKey($url_key) \/\/ you don't need to set it, because Magento does this by default, but you can if you need to\n                    ->setWebsiteIds(array(1)) \/\/ Default Website ID\n                    ->setStoreId(0) \/\/ Default store ID\n                    ->setVisibility(4) \/\/ 4 = Catalog &amp; Search\n                    ->save();\n\n        } catch (\\Exception $e) {\n            $logger->info('Error importing product sku: '.$sku.'. '.$e->getMessage());\n            continue;\n        }\n\n        try {\n            $stockItem = $stockRegistry->getStockItemBySku($sku);\n\n            if ($stockItem->getQty() != $qty) {\n                $stockItem->setQty($qty);\n                if ($qty > 0) {\n                    $stockItem->setIsInStock(1);\n                }\n                $stockRegistry->updateStockItemBySku($sku, $stockItem);\n            }\n        } catch (\\Exception $e) {\n            $logger->info('Error importing stock for product sku: '.$sku.'. '.$e->getMessage());\n            continue;\n        }\n        unset($product);\n    }\n    fclose($file);\n}\n    \n?><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Example CSV for importing new products:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\"sku\",\"name\",\"description\",\"short_description\",\"price\",\"qty\"\n\"test-sku1\",\"Test product name1\",\"Test product description1\",\"Test product short description1\",\"100\",\"20\"\n\"test-sku2\",\"Test product name2\",\"Test product description2\",\"Test product short description2\",\"10\",\"30\"<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">That\u2019s it. Likewise you can also&nbsp;<a href=\"https:\/\/meetanshi.com\/blog\/add-images-to-product-gallery-in-magento-2\/\">Magento 2 add images to product gallery programmatically<\/a>&nbsp;to as an solution to adding images for each product manually in default in Magento 2.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can use the above example with necessary changes as per your business requirements.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do share the solution with Magento community via social media.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Thank you.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Continue Reading:<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/meetanshi.com\/blog\/magento-2-export-products-into-csv\/\">Export Products into CSV Magento 2<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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&#8230;<\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[34],"tags":[],"class_list":["post-946","post","type-post","status-publish","format-standard","hentry","category-magento"],"acf":[],"_links":{"self":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/946","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/comments?post=946"}],"version-history":[{"count":3,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/946\/revisions"}],"predecessor-version":[{"id":14957,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/946\/revisions\/14957"}],"wp:attachment":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/media?parent=946"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/categories?post=946"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/tags?post=946"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}