how to put product into category, data come from csv magento 2

lets say i have this csv file


the F colume is the list of category ids, and the A colume is the sku of product.

we put the csv on the server’ and now we run of our controller, we direct the controller to run the function that handle the job.

the function first get the csv file and loop over the lines.

on each every line we get the categories/

now we check if the product have this category then dont do nothing but he dowsnt have this category we assign the product to the category.

if we dont have this product in the database the it will show us in the end the list of all product sku’s that there is now product in the database


 public function assin_category_to_product_from_csv(){
$csvReader = new \Magento\Framework\File\Csv(new \Magento\Framework\Filesystem\Driver\File());
$data = $csvReader->getData('list_text.csv');

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');

$products_sku_not_exsit = [];

foreach ($data as $lines => $line) {
//$line[0] is product id
//$line[3] is the name of categories

$categories_from_csv = explode(",", $line[5]);
$length_categories_from_csv = count($categories_from_csv);

$sku = (int) preg_replace('/[^0-9]/', '', $line[0]);
$product = $productRepository->get($sku);
}catch (\Magento\Framework\Exception\NoSuchEntityException $e){

array_push($products_sku_not_exsit, $sku);

$categories_from_db_by_product = $product->getCategoryIds(); /*will return category ids array*/
$length_categories_from_db_by_product = count($categories_from_db_by_product);

for($i = 0; $i 0){
foreach($categories_from_db_by_product as $category){
if($category == $categories_from_csv[$i]){

$isIn = true;
break;//we found match
//echo $categories_from_csv[$i] . "is out , ";


//i take all the current categories of the product and add another one and then assin categories to the product

//$product->save();//this option is good when it's not complex product

$bb = $objectManager->get('Magento\Catalog\Api\CategoryLinkManagementInterface');
$bb->assignProductToCategories($product->getSku(), $product->getCategoryIds());

This entry was posted in כללי and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s