Magento - Product Attribute Values - Set Programmatically

Posted by Damodar Bashyal on March 21, 2012

 

I needed to import manufacturers list from oscommerce to magento and this is how i did it, not sure if there is an easy way to do this. Let me know if you know better way to do it.

Lets create a file (manufacturer.php) on the root of the magento installation path, and add below code and run the file. Code is self explanatory I guess :)

<?php
// Let's include mage.php file
require_once 'app/Mage.php';
umask(0);

// Initialize the magento
Mage::app('default');

// Set default values to these variables
$m = array();
$manufacturer = array();
$m_fromdb = array();

// Connect to oscommerce database
mysql_connect("localhost", "technooze_user", "technooze_password") or die(mysql_error());
mysql_select_db("technooze_osalon") or die(mysql_error());

//  Get all the manufacturers from the 'manufacturers' table.
$result = mysql_query("SELECT manufacturers_name FROM manufacturers WHERE `manufacturers_name` != ''") or die(mysql_error());

// Get all the data and save in the array $m_fromdb
while($row = mysql_fetch_array( $result ))
{
    // Let's make them ucwords, if they are not already.
    $manufacturers_name = ucwords($row['manufacturers_name']);
    $m_fromdb[$manufacturers_name] = $manufacturers_name;
}

// Get all the existing manufacturers
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'manufacturer');
foreach ( $attribute->getSource()->getAllOptions(true, true) as $option)
{
	$manufacturer[$option['label']] = $option['label'];
}

// Exclude empty manufacturer lists and then save rest to $m
foreach($manufacturer as $v)
{
    if(empty($v['label']))
    {
	    continue;
    }
    $m[$v['label']] = $v['label'];
}

// We are going to skip existing manufacturers from the new list, so it's not doubled up
$m = array_diff($m_fromdb, $m);

// We must have int keys (specially '0') on the key list 
// else it will throw error 'Default option value is not defined'. 
// sort will take care of it.
sort($m); 

// Now let's utilize Magento's Entity Setup Model
$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();

$option = array();
$entityTypeId = Mage::getModel('catalog/product')->getResource()->getTypeId();
$option['attribute_id'] = $installer->getAttributeId($entityTypeId, 'manufacturer');

foreach($m as $k => $v)
{
	$option['value']['option'.$k][0] = $v;
}
$installer->addAttributeOption($option);

$installer->endSetup();

If it helped you a little please like (+1) and follow us.

 
not published on website


QR Code: Magento - Product Attribute Values - Set Programmatically