Toll Free 88808-24000 sales@treewalkerlabs.com

Sometime we have to import the product from external csv file which is not in magento format. In those cases we would have to write some script in magento to read the csv and create the product Ā programatically through that csv data.Below I have mentioned the way to read the csv and create the product.

# Read data from CSV.– In this I am using my own columns which can be different for you .

[codesyntax lang=”php”]

function parse_csv_file($csvfile) {
        $csv = Array();
		$rowcount = 0;
		if (($handle = fopen($csvfile, "r")) !== FALSE) {
			$max_line_length = defined('MAX_LINE_LENGTH') ? MAX_LINE_LENGTH : 10000;
			$header = fgetcsv($handle, $max_line_length);
			foreach($header as $c=>$_cols) {
				$header[$c] = strtolower(str_replace(" ","_",$_cols));
			}
			$header_colcount = count($header);
			while (($row = fgetcsv($handle, $max_line_length)) !== FALSE) {
				$row_colcount = count($row);
				if ($row_colcount == $header_colcount) {
					$entry = array_combine($header, $row);
					$csv[] = $entry;
				}
				else {
					error_log("csvreader: Invalid number of columns at line " . ($rowcount + 2) . " (row " . ($rowcount + 1) . "). Expected=$header_colcount Got=$row_colcount");
					return null;
				}
				$rowcount++;
			}
			//echo "Totally $rowcount rows found\n";
			fclose($handle);
		}
		else {
			error_log("csvreader: Could not read CSV \"$csvfile\"");
			return null;
		}
		return $csv;
}

[/codesyntax]

You can define this function in some file , which accept path of the csv file as parameter. You can include this file in the script.

# Creating product

[codesyntax lang=”php”]

$id = Mage::getModel('catalog/product')->getIdBySku($csv_data['sku']);
$productModel = Mage::getModel('catalog/product');
$stockItemData	= array();
if($id) {
   $productModel = $productModel->load($id);
   $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productModel);
   $stockItemData = $stockItem->getData();
  
  
}else{
  $productModel->setId(NULL)
               ->setStoreId(1) //you can set data in store scope
			   ->setWebsiteIds(array(1))  //website ID the product is assigned to, as an array
			   ->setAttributeSetId(4) 
			   ->setCreatedAt(strtotime('now'))
			   ->setTypeId('simple');   //ID of a attribute set named 'default';
}

			 
$productModel->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
			     ->setSku($xml_data['sku']);
if($stockItemData){
       $is_in_stock = ($csv_data['availability'] == 'Y') ? 1 : 0; //Stock Availability
	   $stockItem->setData('manage_stock', 1);
	   $stockItem->setData('is_in_stock', ($csv_data['instock'] == 'Y') ? 1 : 0);
	   //$stockItem->setData('use_config_notify_stock_qty', 0);
	   $stockItem->setData('qty', $csv_data['inventory']);
	   $stockItem->setData('product_id',$id);
	   $stockItem->save();
}else{			 
      $productModel->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'=>100, //Maximum Qty Allowed in Shopping Cart
					   'is_in_stock' => ($csv_data['instock'] == 'Y') ? 1 : 0 , //Stock Availability
					   'qty' => $xml_data['inventory'] //qty in stock
				);	
}
/*Code to fetch the category ids based on name :*/
$categoryParentModel = Mage::getResourceModel('catalog/category_collection')
		       ->addFieldToFilter('name', $csv_data['catname'])
	               ->getFirstItem();
$catId = $categoryParentModel->getId();		

$productModel->setPrice($xml_data['price'])
              ->setTaxClassId(0)
			  ->setUpdatedAt(strtotime('now'))
			  ->setDescription($csv_data['desc'])
			  ->setShortDescription($csv_data['short_desc'])
			  ->setCategoryIds(array($catId))
			  ->save();

[/codesyntax]

The above code will create the individual product. Put it in a function “createproduct” and place it in same file as you placed the “parse_csv_function”

Below is the complete code . I have created the functions in functions.php file which I have included in the script.

[codesyntax lang=”php”]

/* the script is inside some directory in the magento root */
error_reporting(E_ALL);
ini_set('display_errors',1);
set_time_limit(0);
$mageFilename = dirname(__FILE__).'/../app/Mage.php';
require_once $mageFilename;
require_once "functions.php";

umask(0);
Mage::app();
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

$csvFile = 'product.csv';
if(file_exists(dirname(__FILE__)."/".$csvFile)) {
	$csv = parse_csv_file($csvFile);
			/* end */
			
	if($csv) {		
		foreach($csv as $_csvdata) {
			 createProduct($_csvdata);
		  
		} // end of the loop
		
		/* @var $indexCollection Mage_Index_Model_Resource_Process_Collection */
		$indexCollection = Mage::getModel('index/process')->getCollection();
		foreach ($indexCollection as $index) {
			/* @var $index Mage_Index_Model_Process */
			$index->reindexAll();
		}
		
	}else{
		echo "<strong>Not data for import.</strong>";
	}
}else{
    echo "<strong>CSV File not available.</strong>";
}

[/codesyntax]