Tuesday, 2 July 2019

Update Category Attribute Programatically in Magento2 using csv

<?php
ini_set('display_errors', 1);
ini_set('memory_limit', '5G');
error_reporting(E_ALL);

use Magento\Framework\App\Bootstrap;

require 'app/bootstrap.php';



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

$objectManager = $bootstrap->getObjectManager();

$category = $objectManager->get(Magento\Catalog\Model\CategoryFactory::class);

$directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');

echo $csv =  $directory->getPath('var').'/category.csv'; //put csv in var directory

$handle = fopen($csv, "r");
if (empty($handle) === false) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        if($data[0]=='category_id') continue;
        try {
            $categoryItem = $category->create()->load($data[0]);
            $categoryItem->setData('custom_attribute', 1);
            $categoryItem->save();
            echo '<br/>Category updated '.$data[0];
        }
        catch (\Exception $e) {
                $this->logger->critical($e->getMessage());
            }
    }
    fclose($handle);
}

?>

No comments:

Post a Comment