Magento 2 – How to Programmatically Update Attribute Fields from CSV

csvmagento2product-attribute

I had a custom script for 1.9 that did this but it does not work on 2.0.

Could someone provide any help or pointers to help get this working.

Once a day I would like the script to update the magento inventory from a CSV files with three columns, the three columns are sku, price qty.

Any help is greatly appreciated.

Here is similar code i used in 1.9 as requested. Any help is appreciated.

 <?php 
/*Move to our working directory
   $home = getenv("HOME");
   if (! $home) {
           chdir('../'); // We hope we are somewhere where this works
   } else {
           chdir($home.'/project/html');
   }*/
$csv = "CSV-File-With-updates.csv";
if (sizeof($argv) > 1) {
$csv = $argv[1];
}
//Turn On Error Reporting
error_reporting(E_ALL | E_STRICT);
//BOOTSTRAP MAGENTO
$mageFilename = '../app/Mage.php';
require_once $mageFilename;

//require_once 'relatedProducts.php';
  Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
Mage::setIsDeveloperMode(true);
umask(0);

//OPEN CSV
if (($handle = fopen($csv, "r")) !== FALSE) {
 while (($data = fgetcsv($handle, 2000, "\t")) !== FALSE) {
    $num = count($data);
    if ($num < 1) continue; // skip blank lines
    $sku = trim($data[0]);
    if ($num < 2) {
        echo "Skipping: ".$sku." not enough fields\n";
        continue;
    }
    $qty = trim($data[1]);
    $price = trim($data[2]);
 // grab the product based on sku.
    $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
    if(!$product) {
        print "Error:  Invalid SKU, ".$sku."\n";
        continue;
    }
    if ($product->getPrice() != $price) {
        $product->setPrice($price);
        $product->save();
    }
// Grab the inventory(stock) model in order to update quantities.
    $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId());
    if ($stockItem->getData('qty') != $qty) {
        $stockItem->setData('qty', $qty);
        if ($qty > 0) {
            $stockItem->setData('is_in_stock', 1);
        }
        $stockItem->save();
    }
}
fclose($handle);

}

Best Answer

Here is solution for Magento 2.

<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';

$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);

$obj = $bootstrap->getObjectManager();

$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$productRepository = $obj->get('Magento\Catalog\Model\ProductRepository');
$stockRegistry = $obj->get('Magento\CatalogInventory\Api\StockRegistryInterface');

$csv = "CSV-File-With-updates.csv";
if (!empty($argv) && sizeof($argv) > 1) {
    $csv = $argv[1];
}
if (($handle = fopen($csv, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 2000, "\t")) !== FALSE) {
        $num = count($data);
        if ($num < 1) {
            continue;
        }
        $sku = trim($data[0]);
        if ($num < 2) {
            echo "Skipping: " . $sku . " not enough fields\n";
            continue;
        }
        $qty = trim($data[1]);
        $price = trim($data[2]);

        try {
            $product = $productRepository->get($sku);
        } catch (\Exception $e) {
            echo "Error:  Invalid SKU, ".$sku."\n";
            continue;
        }

        if ($product->getPrice() != $price) {
            $product->setPrice($price);
            $product->save();
        }

        try {
            $stockItem = $stockRegistry->getStockItemBySku($sku);
        } catch (\Exception $e) {
            echo "Error:  Invalid stock SKU, ".$sku."\n";
            continue;
        }

        if ($stockItem->getQty() != $qty) {
            $stockItem->setQty($qty);
            if ($qty > 0) {
                $stockItem->setIsInStock(1);
            }
            $stockRegistry->updateStockItemBySku($sku, $stockItem);
        }
    }
    fclose($handle);
}