How To Update Bulk Product SKU Using CSV In Magento 2

The product SKU is a unique id for each product in a Magento 2 store. Changing product SKU in bulk is not easy in Magento 2.

However, sometime, it may happen that you need to update bulk product SKU in Magento 2 when you are importing products from a third-party platform.

The below code is the solution for the same.

You can use this code to update product SKU, product price, etc. in bulk in Magento 2 store using the CSV file.

Method to update bulk product SKU using CSV in Magento 2:

<?php
use Magento\Framework\AppInterface;
try {
    require_once __DIR__ . '/app/bootstrap.php';

} catch (\Exception $e) {
    echo 'Autoload error: ' . $e->getMessage();
    exit(1);
}

try {
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $objectManager->get('Magento\Framework\App\State')->setAreaCode('adminhtml');

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager

    $row = 1;
    $csvName = "{file.csv}"; // Here you need to place .csv file path
    $productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');
    if ( ($handle = fopen($csvName, "r")) !== FALSE ) {
        $row = 1;
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            if ( $row == 1 ) {
                $row++;
                continue;
            } // to skip first line if first row is column name.
            $row++;
            try {
                $productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');

                $sku = $data[0]; // this can manage as per your csv.

                $productObj = $productRepository->get($sku);

                $productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
                $productRepository->save($productObj);


            } catch (\Exception $e) {
                echo $e->getMessage();
            }
        }
        fclose($handle);
    }
} catch (\Exception $e) {
    echo $e->getMessage();
}

That’s it.

Do share the post with fellow developers via social media.

Thank you.

Table of Contents