如何在magento中以编程方式导入具有多个属性的可配置产品

时间:2015-11-23 11:03:11

标签: php magento

<?php
/**
* @author stw
* @website http://stw-services.com/
*
*/
header('Content-Type: text/csv; charset=utf-8');
require_once("app/Mage.php");
Mage::app('default');
/*$csv_file = "juliajune_erp/import/products/products.csv"; // Name of your CSV file
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
*/
$row = 0;
$simple_product_counter=0;
$simple_product_sku[]=array();
$simple_product_color[]=array();
$simple_product_size[]=array();
$path = "juliajune_erp/import/products/export/"; 
$latest_ctime = 0;
$latest_filename = '';    
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
    if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
        $latest_ctime = filectime($filepath);
        $latest_filename = $entry;
    }
}
$latestpath = $path.$latest_filename;
if (($handle = fopen($latestpath, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 100000, ",")) !== FALSE) {
       $num = count($data);
       $row++;
      if($data[3] == 'simple')
        {  
            $simpleProduct = Mage::getModel('catalog/product');
            try {
                //echo "set attribute:-".$data[2];echo "<br>";
                        //$simpleProduct->setAttributeSetId(4); //ID of a attribute set named 'default'
                if($data[2]=='Default'){$attribute_set_id=4;}
                $simpleProduct->setAttributeSetId($attribute_set_id); //ID of a attribute set named 'default'
                //echo "product type:-".$data[3];echo "<br>";
                $simpleProduct->setTypeId($data[3]); //product type
                //echo "created time:-".$data[11];echo "<br>";
                $simpleProduct->setCreatedAt($data[11]); //product creation time
                //echo "sku:-".$data[0];echo "<br>";
                $simpleProduct->setSku($data[0]); //SKU
                //echo "name:-".$data[36];echo "<br>";
                $simpleProduct->setName($data[36]); //product name
                //echo "weight:-".$data[59];echo "<br>";
                $simpleProduct->setWeight($data[59]);
                //echo "status:-".$data[50];echo "<br>";
                $simpleProduct->setStatus($data[50]); //product status (1 - enabled, 2 - disabled)
                //echo "tax class id:-".$data[51];echo "<br>";
                $simpleProduct->setTaxClassId($data[51]); //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
                //echo "visibility :-".$data[58];echo "<br>";
                $simpleProduct->setVisibility($data[58]); //catalog and search visibility
                /*----------color------------*/
                $attributeColorCode = 'color';
                $_product = Mage::getModel('catalog/product');
                $attr = $_product->getResource()->getAttribute($attributeColorCode);
                if ($attr->usesSource()) {   $color_id = $attr->getSource()->getOptionId($data[8]); }
                //echo "color :-".$color_id;echo "<br>";
                $simpleProduct->setColor($color_id);
                /*----------size------------*/
                $attributeSizeCode = 'size';
                $_product = Mage::getModel('catalog/product');
                $attr = $_product->getResource()->getAttribute($attributeSizeCode);
                if ($attr->usesSource()) {   $size_id = $attr->getSource()->getOptionId($data[44]); }
                //echo "size :-".$size_id;echo "<br>";
                $simpleProduct->setSize($size_id);

                //echo "price:-".$data[41]; echo "<br>";
                $simpleProduct->setPrice($data[41]); //price in form 11.22
                //echo "msrp enable:-".$data[35];echo "<br>";
                $simpleProduct->setMsrpEnabled(2); //enable MAP
                //echo "msrp display actual price type:-".$data[34];echo "<br>";
                $simpleProduct->setMsrpDisplayActualPriceType(4); //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)

                //echo "description:-".$data[20];echo "<br>";
                $simpleProduct->setDescription($data[20]);
                //echo "short description:-".$data[43];echo "<br>";
                $simpleProduct->setShortDescription($data[43]);


                $mediaArray_simple = array('thumbnail'   => $data[52],'small_image' => $data[45],'image' => $data[25]);
                $importDir_images = Mage::getBaseDir('media') . DS . 'import/';

                //foreach ( $mediaArray_simple as $imageType => $fileName ) {
                    $fileName = $data[25];
                    $filePath = $importDir_images.$fileName;
                    if ( file_exists($filePath) ) { 
                        //$simpleProduct->addImageToMediaGallery($filePath, $imageType, false);
                        $simpleProduct->addImageToMediaGallery($filePath, array('image','thumbnail','small_image'), false, false);
                    }
                //}

                $stockData = $simpleProduct->setStockData(array(
                        'use_config_manage_stock' => $data[74], //'Use config settings' checkbox
                        'manage_stock' => $data[73], //manage stock
                        'is_in_stock' => $data[70], //Stock Availability
                        'qty' => $data[60] //qty
                    )
                );
                //echo "category id:-".$data[4];echo "<br>----------------<br>";
                $simpleProduct->setCategoryIds(array('')); //assign product to categories
                $simpleProduct->save();

            /* using for configurable product */
            $simple_product_sku[$simple_product_counter]=$data[0];
            $simple_product_color[$simple_product_counter]=$data[8];
            $simple_product_size[$simple_product_counter]=$data[44];
            $simple_product_counter++;
            } catch (Exception $e) {
                Mage::log($e->getMessage());
                //echo $e->getMessage();
            }

        }elseif($data[3] == 'configurable'){
            $configProduct = Mage::getModel('catalog/product');
            try {

                //echo "set attribute:-".$data[2];echo "<br>";
                        //$configProduct->setAttributeSetId(4); //ID of a attribute set named 'default'
                if($data[2]=='Default'){$attribute_set_id=4;}
                $configProduct->setAttributeSetId($attribute_set_id); //ID of a attribute set named 'default'
                //echo "product type:-".$data[3];echo "<br>";
                $configProduct->setTypeId($data[3]); //product type
                //echo "created time:-".$data[11];echo "<br>";
                $configProduct->setCreatedAt($data[11]); //product creation time
                //echo "sku:-".$data[0];echo "<br>";
                $configProduct->setSku($data[0]); //SKU
                //echo "name:-".$data[36];echo "<br>";
                $configProduct->setName($data[36]); //product name
                //echo "weight:-".$data[59];echo "<br>";
                $configProduct->setWeight($data[59]);
                //echo "status:-".$data[50];echo "<br>";
                $configProduct->setStatus($data[50]); //product status (1 - enabled, 2 - disabled)
                //echo "tax class id:-".$data[51];echo "<br>";
                $configProduct->setTaxClassId($data[51]); //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
                //echo "visibility :-".$data[58];echo "<br>";
                $configProduct->setVisibility($data[58]); //catalog and search visibility
                //echo "price:-".$data[41]; echo "<br>";
                $configProduct->setPrice($data[41]); //price in form 11.22
                //echo "msrp enable:-".$data[35];echo "<br>";
                $configProduct->setMsrpEnabled(2); //enable MAP
                //echo "msrp display actual price type:-".$data[34];echo "<br>";
                $configProduct->setMsrpDisplayActualPriceType(4); //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)

                //echo "description:-".$data[20];echo "<br>";
                $configProduct->setDescription($data[20]);
                //echo "short description:-".$data[43];echo "<br>";
                $configProduct->setShortDescription($data[43]);

                $mediaArray = array('thumbnail'   => $data[52],'small_image' => $data[45],'image' => $data[25]);
                $importDir_images = Mage::getBaseDir('media') . DS . 'import/product_images/';
                    $fileName = $data[36];
                    $filePath = $importDir_images.$fileName.'.jpg';
                    if ( file_exists($filePath) ) { 
                        $configProduct->addImageToMediaGallery($filePath, array('image','thumbnail','small_image'), false, false);
                    }
                for($img_i=1;$img_i<=4;$img_i++)
                {
                    $importDir_images = Mage::getBaseDir('media') . DS . 'import/product_images/';
                    $fileName = $data[36];
                    $filePath = $importDir_images.$fileName.'_'.$img_i.'.jpg';  
                    if ( file_exists($filePath) ) { 
                    $configProduct->addImageToMediaGallery( $filePath , null, false, false );
                    }
                }


                $stockData = $configProduct->setStockData(array(
                        'use_config_manage_stock' => $data[74], //'Use config settings' checkbox
                        'manage_stock' => $data[73], //manage stock
                        'is_in_stock' => $data[70], //Stock Availability
                    )
                );
                //echo "category id:-".$data[4];echo "<br>----------------<br>";
                $cat_name = substr($data[4], strpos($data[4],'/')+strlen('/'));
                $category = Mage::getResourceModel('catalog/category_collection')
                    ->addFieldToFilter('name', $cat_name);
                //print_r($category->getData());    
                $cat_id = $category->getFirstItem()->getEntityId();
                $configProduct->setCategoryIds(array(2, 5, $cat_id)); //assign product to categories
                /**/
                /** assigning associated product to configurable */
                /**/
                $count_loop = $simple_product_counter;
                $config_color_count=0;
                $config_size_count=0;
                $configurableProductsData=array();
                $configurableProductsData_new=array();
                $configurableProductsDataSize=array();
                $attribute_colorid ="";
                for($i=0;$i<$count_loop;$i++)
                {
                        $attributeColorCode = 'color';
                        $attribute_details = Mage::getSingleton("eav/config")->getAttribute('catalog_product', $attributeColorCode);
                        $attribute = $attribute_details->getData();
                        $attribute_colorid = $attribute['attribute_id'];
                        $_product = Mage::getModel('catalog/product');
                        $attr = $_product->getResource()->getAttribute($attributeColorCode);
                        if ($attr->usesSource()) {   $color_id = $attr->getSource()->getOptionId($simple_product_color[$config_color_count]);   }
                        $current_product_id = Mage::getModel("catalog/product")->getIdBySku( $simple_product_sku[$config_color_count] ); 
                        $configurableProductsData[$current_product_id] = array( //['product_id'] = id of a simple product associated with this configurable
                            '0' => array(
                                'label' => $simple_product_color[$config_color_count], //attribute label
                                'attribute_id' => $attribute_colorid, //attribute ID of attribute 'color' in my store
                                'value_index' => $color_id, //value of 'Green' index of the attribute 'color'
                                'is_percent' => '0', //fixed/percent price for this option
                                'pricing_value' => '0' //value for the pricing
                            )
                        );
                    $config_color_count++;
                }

                for($i=0;$i<$count_loop;$i++)
                {
                        /*color */
                        $attributeColorCode = 'color';
                        $attribute_details_color = Mage::getSingleton("eav/config")->getAttribute('catalog_product', $attributeColorCode);
                        $attribute_color = $attribute_details_color->getData();
                        $attribute_colorid = $attribute_color['attribute_id'];
                        /*---*/
                        $attributesizeCode = 'size';
                        $attribute_details = Mage::getSingleton("eav/config")->getAttribute('catalog_product', $attributesizeCode);
                        $attribute = $attribute_details->getData();
                        $attribute_sizeid = $attribute['attribute_id'];
                        $_product = Mage::getModel('catalog/product');
                        $attr = $_product->getResource()->getAttribute($attributesizeCode);
                        if ($attr->usesSource()) {   $size_id = $attr->getSource()->getOptionId($simple_product_size[$config_size_count]);  }
                        $current_product_id = Mage::getModel("catalog/product")->getIdBySku( $simple_product_sku[$config_size_count] ); 
                        $configProduct->getTypeInstance()->setUsedProductAttributeIds(array($attribute_sizeid,$attribute_colorid)); //attribute ID of attribute 'size' in my store
                        $configurableAttributesData = $configProduct->getTypeInstance()->getConfigurableAttributesAsArray();
                        //$configurableAttributesData[0]['id']=$current_product_id;
                        //$configurableAttributesData[1]['id']=$current_product_id;
                        echo "<pre>";print_r($configurableAttributesData);
                        $configProduct->setCanSaveConfigurableAttributes(true);
                        $configProduct->setConfigurableAttributesData($configurableAttributesData);

                        $configurableProductsData_new[$current_product_id] = array( //['920'] = id of a simple product associated with this configurable
                            '1' => array(
                                'label' => $simple_product_size[$config_size_count], //attribute label
                                'attribute_id' => $attribute_sizeid, //attribute ID of attribute 'size' in my store
                                'value_index' => $size_id, //value of 'Green' index of the attribute 'size'
                                'is_percent' => '0', //fixed/percent price for this option
                                'pricing_value' => '0' //value for the pricing
                            )
                        );
                    $config_size_count++;

                }
                //echo "<pre>";print_r($configurableProductsData_new);
                $configProduct->setConfigurableProductsData($configurableProductsData_new);
                //echo "<pre>";print_r($configurableProductsData);
                $configProduct->setConfigurableProductsData($configurableProductsData);

                $configProduct->save();
                $simple_product_counter=0;
                unset($simple_product_sku); 
                unset($simple_product_color); 
                unset($simple_product_size); 
                echo 'success<br>';
            } catch (Exception $e) {
                Mage::log($e->getMessage());
                echo $e->getMessage();
            }
        }
    }
    fclose($handle);
}
/* @var $indexCollection Mage_Index_Model_Resource_Process_Collection */
/*
$indexCollection = Mage::getModel('index/process')->getCollection();
foreach ($indexCollection as $index) {

    $index->reindexAll();
}
*/
?>

我已经完成了以编程方式导入产品,并且在磁控管理面板上正确显示了相关产品。此外,我已经完成了索引和清除缓存,但现在,我正在前端显示产品的问题。如果我只是保存并继续编辑可配置产品的相关产品,那么在重新索引之后它将显示在前端。请帮我解决这个问题

0 个答案:

没有答案