Import magento 2 products programmatically

This tutorial explains how to import magento 2 products programmatically. This tutorial shows how to initialise the import script, read data from CSV, import magento 2 products, set main and default image programmatically.

The following code created the simple products programmatically. Please also refer the tutorial which explains how to import configurable products programmatically.


import_magento_2_products_programmatically

Step by step explanation

  • Initialise Script
  • Read CSV
  • Import magento 2 products
  • Set Main Image Programmatically
  • Add additional images programmatically

Initialise Script

As the first create the importproducts.php file inside the script folder in the magento root directory.Then establish the database connection as shown below.

<?php
define('DS', DIRECTORY_SEPARATOR); 
use \Magento\Framework\App\Bootstrap;

include('../app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$app_state = $objectManager->get('\Magento\Framework\App\State');
$app_state->setAreaCode('frontend');

$productsData = getProducts();
importSimpleProducts( $productsData , $objectManager );

Read CSV

This step reads the products data from the CSV.

function getCategories()
{
    $file = 'csv/categories.csv';
    $arrResult = array();
    $headers = false;
    $handle = fopen($file, "r");
    if (empty($handle) === false) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            if (!$headers) {
                $headers[] = $data;
            } else {
                $arrResult[] = $data;
            }
        }
        fclose($handle);
    }
    return $arrResult;
}

Import magento 2 products

The above function reads the data from the CSV and return the data in an array. The following code iterate through the array and create the products as show above.

/*
 * Import Simple Products
 */
function importSimpleProducts( $importProducts, $objectManager ) {
      
    // Path to media folder        
    $filesystem = $objectManager->create('Magento\Framework\Filesystem');
    $mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
    $mediaPath = $mediaDirectory->getAbsolutePath();
    
    foreach( $importProducts as $importProduct ) {
        
        try {  

            $product = $objectManager->create('\Magento\Catalog\Model\Product');
            $product->setWebsiteIds(array(1));
            $product->setAttributeSetId(4);
            $product->setTypeId('simple');
            $product->setCreatedAt(strtotime('now')); 
            $product->setName($importProduct[1]); 
            $product->setSku($importProduct[3]);
            $product->setWeight($importProduct[16]);
            $product->setStatus(1);
            $category_id= array(30,24);
            $product->setCategoryIds($category_id); 
            $product->setTaxClassId(0); // (0 - none, 1 - default, 2 - taxable, 4 - shipping)
            $product->setVisibility(4); // catalog and search visibility
            $product->setColor(24);
            $product->setPrice($importProduct[11]) ;
            $product->setCost(1); 
            $product->setMetaTitle($importProduct[1]);
            $product->setMetaKeyword($importProduct[26]);
            $product->setMetaDescription($importProduct[28]);
            $product->setDescription($importProduct[27]);
            $product->setShortDescription($importProduct[27]);

            $product->setStockData(
                array(
                'use_config_manage_stock' => 0, 
                'manage_stock' => 1, // manage stock
                'min_sale_qty' => 1, // Shopping Cart Minimum Qty Allowed 
                'max_sale_qty' => 2, // Shopping Cart Maximum Qty Allowed
                'is_in_stock' => 1, // Stock Availability of product
                'qty' => (int)$importProduct[6]
                )
            );

            
            $product->save();
            echo "Upload simple product id :: ".$product->getId()."\n";
        }
    catch(Exception $e)
    {
        echo 'Something failed for product import ' . $importProduct[1] . PHP_EOL;
        print_r($e);
    }
}   
}

Set Main Image and Additional Images magento 2

Copy the images the media folder and following code set the images as shown below.Please click here for detailed explanation.

// Absolute path

    $filesystem = $objectManager->create('Magento\Framework\Filesystem');
    $mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
    $mediaPath = $mediaDirectory->getAbsolutePath();
    

 $mainImage = $importProduct[9];
// Main Image
    if ($mainImage) {
        $image_directory = $mediaPath . DS . 'data' . DS . $mainImage;
        if (file_exists($image_directory)) {
            $product->setMediaGallery(array('images' => array(), 'values' => array()))//media gallery initialization
                ->addImageToMediaGallery($image_directory, array('image', 'thumbnail', 'small_image'), false, false);//assigning image, thumb and small image to media gallery
        } 
        else {
            $image_directory = $mediaPath . 'data' . DS . 'comingsoon.jpg';
            $product->setMediaGallery(array('images' => array(), 'values' => array()))//media gallery initialization
                ->addImageToMediaGallery($image_directory, array('image', 'thumbnail', 'small_image'), false, false);
        }
    }

    // additional images
    if ($importProduct[29] != '') {
        $addImages = explode(",", trim($importProduct[29]));
        foreach ($addImages as $additional_image) {
            $image_directory = $mediaPath .DS.'data'.DS. trim($additional_image);
            if (file_exists($image_directory)) {
                $product->addImageToMediaGallery($image_directory, null, false, false);
            } 
            else {
                $image_directory = $mediaPath . 'data' . DS . 'comingsoon.jpg';
                $product->addImageToMediaGallery($image_directory, null, false, false);
            }
        }
        echo 'Additional images for product ' . $product->getName() . ' ' . $product->getId() . ' imported successfully' . PHP_EOL;
    }

import-product-image-magento-2

Please click here to find out how to import configurable products programmatically.

If you have any further queries please leave a reply.

Share this Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

*