1

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

}

  • Please post your custom code script here – Ankit Shah Oct 5 '16 at 1:39
  • have you already products are there in magento admin? if you want to update attribute inside product you must have first product in system afterthat you can create csv file and update each sku value. – Rakesh Jesadiya Oct 5 '16 at 4:59
  • @AnkitShah Hello. Ankit. I have updated my question to inlude the code that worked for Magento 1.9. It would grab the products based on sku and then update the price and qty. Any help is appreciated getting this to work on magento 2. thanks. – 305David Oct 19 '16 at 13:31
  • @AnkitShah Could you take a second look at this problem, I have found little solutions online to Magento 2 programatically import export like the code I have above for Magento 1.9. Thanks – 305David Nov 4 '16 at 13:23
0

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

You may simply do it from Magento 2 admin. Prepare CSV file with columns SKU, QTY and PRICE and import that at

Admin >> System >> Import  
Entity Type = Product  
Import Behavior = Add/Update
  • Thank you sir that is helpful but unfortunately I seek a scripting approach to this task. – 305David Oct 5 '16 at 13:38
0

Ran into the same issue here. Updating delivery, backorders like below. The partial below might help you and point in the right direction.

    $msku = $row['SKU'];
    $status_voorraad = $row['status_voorraad'];
    $alldata = array(
        "product" => array(
            "sku" => $msku,
            "extension_attributes" => array(
                "stock_item" => array(
                    "is_in_stock" => true,
                    "use_config_backorders" => false,
                    "backorders" => $status_voorraad
                )
            ),
            "custom_attributes" => [array(
                "attribute_code" => "delivery",
                "value" => $csv_delivery
            )]
        )
    );
    $alldata = json_encode($alldata);
    $requestUrl = $api->getAuth('domain') . '/all/V1/products/'.$sku;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.