How to Import Product Data Programmatically In Magento 2 (Skip if SKU exist)

How to Import Product Data Programmatically In Magento 2 (Skip if SKU exist)

Steps to Import Product Data Programmatically In Magento 2:

Step 1: Create a CSV file at the below path

pub/import/importProduct.csv

image.png

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

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$file = fopen('import/importProduct.csv', 'r', '"'); // set path to the CSV file
if ($file !== false)
{

    // while ($row = fgetcsv($file, 3000, ",") )
    // {
    //     echo "<pre>";
    //     print_r($row);
    //     echo "</pre>";
    // }
    // die('dd');
    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;

    $filterData = [];

    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;
        }


        if($product->getIdBySku($sku)) {
            echo 'exit';    
        }else{

            $filterData[] = array(
                'SKU' => $data['SKU'],
                'name' => $data['Description'],
                'description' => $data['Description'],
                'shortDescription' => $data['Description'],
                'qty' => 20,
                'Price' => $data['Price'],
            );
            // echo "not exist";
            $name = $data['Description'];
            $description = $data['Description'];
            $shortDescription = $data['Description'];
            $qty = 20;
            $price = $data['Price'];

            try
            {
                $product->setTypeId('simple') // product type
                        ->setStatus(2) // 1 = enabled
                        ->setAttributeSetId(44) // temp_product_set
                        ->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);
}    

// echo "<pre>";
// print_r($filterData);
// echo "</pre>";
// die('die');
?>

you can run import using cron or manual

cron for every 2 mints

*/2 * * * * /usr/bin/curl -s https://example.com/import.php &> /dev/null

Did you find this article valuable?

Support Mandeep Singh by becoming a sponsor. Any amount is appreciated!