Change Product SKU Programatically In Magento



Suppose you have imported the products from the third party into the Magento and there are several thousand products and you want to change the product SKUs but it will take alot of time to change the products SKU manually Here in this post I am describing how to create the script to update the SKUs of the products into the Magento or we can say change of the products SKUs Programmatically in Magento.

Step 1. Create a file on the Magento root suppose here I have created the file named as skuconverter.php
Step 2. Now put all the codes below into this file

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
set_time_limit(0);
ini_set("memory_limit","2048M");

// Let's include mage.php file
require_once 'app/Mage.php';
umask(0);

// Initialize the magento
Mage::app('admin');
?>

<?php $prCollection = Mage::getModel('catalog/product')->getCollection(); ?>

<?php foreach($prCollection as $products): ?>
	<?php
		$productId = $products->getId();

		//Loading of the product information
		$product =  Mage::getModel('catalog/product')->load($productId);

		//Fetching Old Sku
		$product_sku = $product->getSku();

		//Creating the new Sku Here I have created the SKU with the combination of Old Product Sku and product Id.
		$product_sku_new = $product_sku.$product_id;

		//Saving of the New Sku into the Magento
		$product->setSku($product_sku_new);
		$product->save();
		echo $product_id. " Has been updated successfully. \n";
	?>
<?php endforeach; ?>

Step 3. Now open the website url and run the script but please remember that if you are dealing with the heavy database don’t run the script on the browser use the Terminal and run the script through the terminal.

Step 4. For running script through the terminal Navigate to the Folder and run the commands below:

php skuconverter.php

Now wait and enjoy the Magento Coding.

Hop it helps. Thanks.