Pragmatically Upload product in magento 2?

<?php
use Magento\Framework\App\Bootstrap;
include(‘app/bootstrap.php’);
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$objectManager1 = Magento\Framework\App\ObjectManager::getInstance();
$directoryList = $objectManager1->get(‘\Magento\Framework\App\Filesystem\DirectoryList’);
$path = $directoryList->getPath(‘media’);
$state = $objectManager->get(‘Magento\Framework\App\State’);
$state->setAreaCode(‘frontend’);
$myarray = glob(“Book1.csv”);
usort($myarray, create_function(‘$a,$b’, ‘return filemtime($a) – filemtime($b);’));
if(count($myarray)){
/*This will create an array of associative arrays with the first row column headers as the keys.*/
$csv_map = array_map(‘str_getcsv’, file($myarray[count($myarray)-1]));
array_walk($csv_map, function(&$a) use ($csv_map) {
$a = array_combine($csv_map[0], $a);
});
array_shift($csv_map); # remove column header

$message = ”;
$count = 1;
foreach($csv_map as $data){
$_product = $objectManager->create(‘Magento\Catalog\Model\Product’);
$_product->setName(trim($data[‘Name’]));
$_product->setTypeId(‘simple’);
$_product->setAttributeSetId(4);
$_product->setSku(trim($data[‘Sku’]));
$_product->setWebsiteIds(array(1));
$_product->setVisibility(4);
$_product->setPrice(trim($data[‘MSRP’]));
$_product->setShortDescription(trim($data[‘Short Description’])); // add text attribute
$_product->setDescription(trim($data[‘Long Description’])); // add text attribute
$img_url = trim($data[‘large_image’]);

$lastWord = substr($img_url, strrpos($img_url, ‘/’) + 1);

copy($img_url, ‘pub/media/product/’.$lastWord);
$dir = $directoryList->getPath(‘media’).’/product/’;
$imgpath = $dir.$lastWord;
//echo $imgpath; die;
//$_product->addImageToMediaGallery($imgpath, array(‘image’,’thumbnail’,’small_image’), false, false);
$_product->addImageToMediaGallery($imgpath, array(‘image’, ‘small_image’, ‘thumbnail’), false, false);
//$_product->setImage($imgpath);
//$_product->setSmallImage($imgpath);
//$_product->setThumbnail($imgpath);
$_product->setStockData(array(
‘use_config_manage_stock’ => 0, //’Use config settings’ checkbox
‘manage_stock’ => 1, //manage stock
‘min_sale_qty’ => 1, //Minimum Qty Allowed in Shopping Cart
‘max_sale_qty’ => 2, //Maximum Qty Allowed in Shopping Cart
‘is_in_stock’ => 1, //Stock Availability
‘qty’ => 100 //qty
)
);

$_product->save();

}
echo’sucess’;
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *