1

I have created custom import script for simple product csv import in magento. It is working fine for the newly products. But I want to update the products if sku already exists. How can I achieve this? I am using the below code :

<?php  
error_reporting(0);

ini_set('max_execution_time', 2000);
ini_set('auto_detect_line_endings', true);
require_once('app/Mage.php'); //Path to Magento

umask(0);

Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(0)); 
$data = glob("customupload/*.csv");  
$fileList = array();
foreach ($data as $file) {
    $fileList[filemtime($file)] = $file;
}
ksort($fileList);
$myarray = array();
foreach($fileList as $key => $val){
    $myarray[] = $val;
}
$list=array();
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]));
    $list = explode('/', $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
    /*End*/

    $message = '';
    $count   = 1;
    foreach($csv_map as $data){
        try {

        $product = Mage::getModel('catalog/product'); 

        $entityTypeId = Mage::getModel('eav/entity')
                        ->setType('catalog_product')
                        ->getTypeId();
        $attributeSetName   = $data['attribute set'];
        $attributeSetId     = Mage::getModel('eav/entity_attribute_set')
                                ->getCollection()
                                ->setEntityTypeFilter($entityTypeId)
                                ->addFieldToFilter('attribute_set_name', $attributeSetName)
                                ->getFirstItem()
                                ->getAttributeSetId();

        $product->setAttributeSetId($attributeSetId); // need to look this up 

        $product->setTaxClassId(0); // taxable goods

        $product->setVisibility(4); // catalog, search

        $product->setStatus(1); // enabled

        $product->setWebsiteIDs(1); 

        $product->setStoreId(1);    

        $product->setTypeId('simple');

        $product->setWarranty('Lifetime');

        // assign product to the default website
        $product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));  


        // configure stock
        $product->setStockData(array(
            'use_config_manage_stock' => 1, // use global config ?
            'manage_stock'            => 0, // shoudl we manage stock or not?
            'is_in_stock'             => 1 
            /*'qty'                     => 2,*/
        ));  
        $mediaArray = array(
            'thumbnail'   => $data['image'],
            'small_image' => $data['image'],
            'image'       => $data['image']
        );

        // Remove unset images, add image to gallery if exists
        $importDir = Mage::getBaseDir('media') . DS . 'import/product/';

        foreach ( $mediaArray as $imageType => $fileName ) {
            $filePath = $importDir . $fileName;
            if ( file_exists($filePath) ) {
                try {
                    $product->addImageToMediaGallery($filePath, $imageType, false);
                } catch (Exception $e) {
                    echo $e->getMessage();
                }
            } else {
                echo "Product does not have an image or the path is incorrect. Path was: {$filePath}<br/>";
            }
        }
        //set category

        $_category = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name', $data['Category'])->getFirstItem();

        $cat1= $_category->getId();
        $expcategory = explode('/',$data['sub category']); 
        $allsubcatid = array();

        foreach($expcategory as $_cat2) 
        {

            $_category = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name', $_cat2)->getFirstItem();

            $allsubcatid[] = $_category->getId(); 

        } 
        //echo '<pre>'; print_r($allsubcatid);die;
        $product->setCategoryIds(array($cat1,$allsubcatid));

        $attribute = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', 'manufacturer');
        $attributeValue = Mage::getResourceModel('eav/entity_attribute_option_collection')
                        ->setAttributeFilter($attribute->getData('attribute_id'))
                        ->setStoreFilter(0, false);
         foreach($attributeValue as $option)    
        {
            if (strtolower($option['value']) == strtolower($data['manufacturer'])) {
                $manufacturer =  $option['option_id'];
            }
        }
        // finally set custom data

        foreach($data as $key => $val){ 
            if($key != 'Category'){
                $capitalword = ucwords(trim($key));
                $remove_hyphen = str_replace(' ','',trim($capitalword)); 
                $setdata = $remove_hyphen; 
                $setdatas = set.$setdata; 
                $product->$setdatas($val); 
            }
        }
        $product->setManufacturer($manufacturer);   
        $product->save();

        }catch (Exception $e) {

            Mage::log($e->getMessage(), null, 'configurableProductsDataError.log', true);
        }
        $count++;
        $c .= $count."<br>"; 
        if($count ==1){ break; } 
    }

        echo "Success";
}

?>
 <?php

rename("customupload/".$list[1], "customupload/uploaded/".$list[1]);
?>
  • Where you create product model there ,check product is existing,by checking like $product = Mage::getModel('catalog/product')->loadBySku($sku); and put that $ product in if condition and if product already then no need to create product model direct use $product and set value to it and save that – user52581 Apr 22 '17 at 12:09
0

Try Using

$_product = Mage::getModel('catalog/product')->loadByAttribute('sku',$data['sku']);

Or

$product = Mage::getModel('catalog/product');
$product->load($product->getIdBySku($data['sku']));

If the product is found it will load the product and return you the model. If not it will return you an empty model.

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.