Tuesday, February 24, 2015

Programmatically creating importing simple product

To add import Magento simple products programmatically:

The following script will create import the product with image, price, weight, description, related products, categories, inventory and more information.

<?php
if (php_sapi_name() !== 'cli' || !empty($_SERVER['REMOTE_ADDR'])) {
  echo "Must be called from the command line.";
  exit(1);
}

ini_set('max_execution_time', 28800);

require_once '/www/magento1.9.1/app/Mage.php';

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
#Mage::app();

importCar();

function importCar() {
  $carSizeArr = array_flip(myGetAttributeOptionArr('car_size'));
  $carColorArr = array_flip(myGetAttributeOptionArr('car_color'));

  $rowArr = explode("\n", file_get_contents('data_car.txt'));

  $count = 0;

  foreach ($rowArr as $row) {
    if (empty($row)) {
      continue;
    }

    list($itemName, $itemNum, $weight, $price, $size, $color) = explode("\t", $row);

    $itemImage = '/www/magento1.9.1/skin/frontend/my/default/images/items/3char/' . $itemNum . '.png';

    if (empty($carSizeArr[$size])) {
      echo '[ERROR] ' . $size . ' no such size.' . PHP_EOL;
      continue;
    }

    if (empty($carColorArr[$color])) {
      echo '[ERROR] ' . $color . ' no such color.' . PHP_EOL;
      continue;
    }

    if (file_exists($itemImage) !== TRUE) {
      echo '[ERROR] ' . $itemImage . ' not exist.' . $itemName . PHP_EOL;
      continue;
    }

    $sizeId = $carSizeArr[$size];
    $colorId = $carColorArr[$color];

    $prodObj = array(
      'itemNum' => $itemNum,
      'itemName' => $itemName,
      'categoryIds' => array(4, 5),
      'attributeSetId' => 9, // default is 4.
      'car_size' => $sizeId,
      'car_color' => $colorId,
      'weight' => $weight,
      'price' => $price,
      'itemImage' => $itemImage,
      'relatedLinkData' => array(
        1 => array('position' => 0),
        2 => array('position' => 0),
      ),
    );

    myAddProduct($prodObj);
    #break;

    $count++;
  }

  echo $count . ' records imported.' . PHP_EOL;
}

function myGetAttributeArrByAttributeSet($attributeSetId) {
  $attributes = Mage::getModel('catalog/product_attribute_api')->items($attributeSetId);

  foreach($attributes as $_attribute){
    print_r($_attribute);
  }
}

function myGetAttributeOptionArr($attributeCode) {
  $outArr = array();
  $optArr = Mage::getSingleton('eav/config')->getAttribute('catalog_product', $attributeCode)->getSource()->getAllOptions();

  foreach ($optArr as $val) {
    if (empty($val['value']) || empty($val['label'])) {
      continue;
    }

    $outArr[$val['value']] = $val['label'];
  }

  return $outArr;
}

function myAddProduct($prodObj) {
  try {
    $product = Mage::getModel('catalog/product');
    $product
      #->setStoreId(1) //you can set data in store scope
      ->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
      ->setAttributeSetId($prodObj['attributeSetId']) //ID of a attribute set named 'default'
      ->setTypeId('simple') //product type
      ->setCreatedAt(strtotime('now')) //product creation time
      #->setUpdatedAt(strtotime('now')) //product update time
      ->setSku($prodObj['itemNum']) //SKU
      ->setName($prodObj['itemName']) //product name
      ->setWeight($prodObj['weight'])
      ->setStatus(1) //product status (1 - enabled, 2 - disabled)
      ->setTaxClassId(2) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
      ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
      #->setManufacturer(28) //manufacturer id
      #->setColor(24)
      #->setNewsFromDate(strtotime('now')) //product set as new from
      #->setNewsToDate('06/30/2015') //product set as new to
      #->setCountryOfManufacture('AF') //country of manufacture (2-letter country code)
      ->setPrice($prodObj['price']) //price in form 11.22
      #->setCost(22.33) //price in form 11.22
      #->setSpecialPrice(3.44) //special price in form 11.22
      #->setSpecialFromDate(strtotime('now')) //special price from (MM-DD-YYYY)
      #->setSpecialToDate('06/30/2015') //special price to (MM-DD-YYYY)
      #->setMsrpEnabled(1) //enable MAP
      #->setMsrpDisplayActualPriceType(1) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
      #->setMsrp(99.99) //Manufacturer's Suggested Retail Price
      #->setMetaTitle('test meta title')
      #->setMetaKeyword('testproduct')
      #->setMetaDescription('test meta description')
      ->setDescription($prodObj['itemName'])
      ->setShortDescription($prodObj['itemName'])
      ->setMediaGallery (array('images'=>array (), 'values'=>array ())) //media gallery initialization
      ->addImageToMediaGallery($prodObj['itemImage'], array('image','thumbnail','small_image'), false, false) //assigning image, thumb and small image to media gallery
      ->setStockData(array(
          'use_config_manage_stock' => 1, //'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
      ))
      ->setCategoryIds($prodObj['categoryIds']) //assign product to categories
      ->setRelatedLinkData($prodObj['relatedLinkData']) // related products
      ;
    $product->save();

    if (isset($prodObj['walker_size'], $prodObj['walker_color']) && is_numeric($prodObj['walker_size']) && is_numeric($prodObj['walker_color'])) {
      $product->setData('car_size', $prodObj['car_size'])->getResource()->saveAttribute($product, 'car_size');
      $product->setData('car_color', $prodObj['car_color'])->getResource()->saveAttribute($product, 'car_color');
    }
  }
  catch (Exception $e) {
    Mage::log($e->getMessage());
  }
}
?>

Reference:

http://inchoo.net/magento/programming-magento/programatically-manually-creating-simple-magento-product/
http://www.magentogeek.com/create-a-simple-product-magento-programmatically/

No comments: