How to load stock levels into Magento from a CSV file

Feb 9, 2011

Create a module and add a method that you call periodically and throw the following code in. To get started [create your own magento module][1] and then you can use the code below to read a CSV file and set properties on the magento products.

// prepare to load products
$product = Mage::getModel('catalog/product');

// read CSV file and load each product and update quantity
$row = 1;
if (($handle = fopen("stockfile.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $sku = $data[0];
        $qty = (int)$data[1];

        // try and load the SKU
        $p = $product->loadByAttribute('sku',$sku);
        if ($p) {
            // get product's stock data such quantity, in_stock etc
            $productId = $p->getIdBySku($sku);
            $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
            $stockItemId = $stockItem->getId();
            $stock = array();

            // then set product's stock data to update
            if (!$stockItemId) {
                $stockItem->setData('product_id', $product->getId());
                $stockItem->setData('stock_id', 1);
            } else {
                $stock = $stockItem->getData();
            }

            $stockItem->setData('qty', $qty);
            if ($qty > 0) {
                $stockItem->setData('is_in_stock', 1);
            } else {
                $stockItem->setData('is_in_stock', 0);
            }
            $stockItem->setData('manage_stock', 1);
            $stockItem->setData('use_config_manage_stock', 1);

            // call save() method to save your product with updated data
            try{
                $stockItem->save();
                $product->save($p);
            } catch (Exception $ex) {
                // handle the error here!!
            }

            unset($stockItem);
            unset($p);

        } else {
            fwrite($fh, "SKU not found: ".$sku."\n");
        }
    }
    fclose($handle);
}

[1]: /2011/02/creating-magento-module/