Author:Kostas Sp Published On:September 11, 2014 Under:Magento
This is How you can insert products programmatically in Magento! There is also a CSV file which will have to be on the magento local folder.
Α csv to array function which will prepare the entry script to Magento.
Check step by step the code and read also the comments.It will help you a lot.
<?php header('Content-Type: text/html; charset=utf-8'); require 'app/Mage.php'; if (!Mage::isInstalled()) { echo "Application is not installed yet, please complete install wizard first."; exit; } // Only for urls // Don't remove this $_SERVER['SCRIPT_NAME'] = str_replace(basename(__FILE__), 'index.php', $_SERVER['SCRIPT_NAME']); $_SERVER['SCRIPT_FILENAME'] = str_replace(basename(__FILE__), 'index.php', $_SERVER['SCRIPT_FILENAME']); Mage::app('admin')->setUseSessionInUrl(false); umask(0); error_reporting(E_ALL | E_STRICT); $mageFilename = 'app/Mage.php'; require_once $mageFilename; Mage::setIsDeveloperMode(true); umask(0); Mage::app(); Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID)); if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br>"; } else { echo "<p>File Name: " . $_FILES["file"]["name"] . "<br>"; echo "File Type: " . $_FILES["file"]["type"] . "<br>"; echo "File Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>"; echo "File temporary folder: " . $_FILES["file"]["tmp_name"]."</p>"; if (file_exists("uploads/" . $_FILES["file"]["name"])) { echo "<strong> '".$_FILES["file"]["name"] . "' already exists. </strong>"; $f = "uploads/" . $_FILES["file"]["name"]; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]); echo "Stored in: " . "uploads/" . $_FILES["file"]["name"]; $f = "uploads/" . $_FILES["file"]["name"]; } echo "<br><br>"; } /** * @link http://gist.github.com/385876 */ function csv_to_array($filename='', $delimiter=',') { if(!file_exists($filename) || !is_readable($filename)) //return FALSE; echo 'return False'; $header = NULL; $data = array(); if (($handle = fopen($filename, 'r')) !== FALSE) { while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) { if(!$header) { $header = $row; } else { echo $row[1].' '; echo count($header); echo '-'; echo count($row); echo '<br>'; $data[] = array_combine($header, $row); } } fclose($handle); } return $data; } $arr = csv_to_array($f); foreach ($arr as &$a) { print '<strong>- - - '.mb_convert_encoding($a['SKU'], "UTF-8").' - - -</strong>'; newSimpleProduct($a['SKU'], mb_convert_encoding($a['Product Name'],"UTF-8"),$a['Reseller Net Price'], $a['Net Price'], $a['Tax'] ,$a['Inhoud'], $a['file picture'] , $a['Category'] , $a['Short description']); } // required for product attributes function trim_value(&$value) { $value = trim($value); } function newSimpleProduct($sku, $name, $reseller_net_price, $net_price , $tax ,$inhoud, $img , $category , $short_description) { // Tax if ($tax == '0,06') { $taxvalue = 5; } // 5 is the option value of 6% BTW NL in the backend else if ($tax == '0,21') { $taxvalue = 6; } // 6 = 21% BTW NL is the option value of 6% BTW NL in the backend else { $taxvalue = 0; } // # 0 = default tax class // needed for simple products --- 2 =taxable goods kai 4 shiping products //get category model $category_model = Mage::getModel('catalog/category')->loadByAttribute('name',$category); $catid = $category_model->getId(); //get category id $product = new Mage_Catalog_Model_Product(); if(!$product->getIdBySku($sku)) { // Build the product $product->setSku($sku); $product->setName($name); $product->setTaxClassId($taxvalue); // # 0 = default tax class // needed for simple products --- 2 =taxable goods kai 4 shiping products $product->setAttributeSetId('4');# 9 is for default $product->setTypeId('simple'); //$product->setCategoryIds(array(42)); # some cat id's, $product->setCategoryIds($catid); # gets the category from the name $product->setWebsiteIDs(array(1)); # Website id, 1 is default $product->setShortDescription( $short_description); // NEEDED for products short description $product->setPrice($net_price); # Set some price $product->setinhoud($inhoud); // for simple: VISIBILITY_NOT_VISIBLE, bundle: VISIBILITY_BOTH $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH); $product->setStatus(1); $product->setStockData(array( 'is_in_stock' => 1, 'qty' => 99999 )); $im_url_path = Mage::getBaseUrl('media').'images/'.$img.'.JPG'; $im_absolute_path = Mage::getBaseDir('media') . DS . 'dnhproductimages/'.$img.'.JPG'; echo $im_absolute_path; $product->setMediaGallery (array('images'=>array (), 'values'=>array ())); // setStoreID(0) is Default Value $product->setStoreId(0)->addImageToMediaGallery($im_absolute_path, array ('image','small_image','thumbnail'), false, false); // line 4 // end img $product->setCreatedAt(strtotime('now')); // Reseller Group PRICE //// $product->setData('group_price',array ( array ( "website_id" => 0, // 0 for All websites - 1 is Main Web site Id "cust_group" => 4, // 4 are Resellers id in the backend "price" => $reseller_net_price // price in Euros ))); try { $product->save(); } catch (exception $e) { //Handle the error echo "<div>".$e."</div>"; } } else { print '<div style="color:red;">'; print 'SKU "'.$sku.'" already exists, stored with ID-number: "'.$product->getIdBySku($sku) ; print '"</div>'; } } ?> |