HummingbirdUK main logo

Coding solutions to business problems

About us

We use code to create solutions to business challenges, bottle-necks and headaches.

If you think your business has a problem that can be solved through code, we are happy to chat things through without any obligation.

Get in touch

Export attribute values from Magento

Home / Blog / Export attribute values from Magento

Written by Giles Bennett

Occasionally you may need to export the values of a Magento attribute programatically - perhaps into a spreadsheet so you can check them, or do something else.

It's not too difficult to do with a simple script, provided that (a) the attribute is of the select / dropdown type, and (b) you know the attribute code. You can find the latter under Catalog / Attributes / Manage Attributes in the admin panel.

Armed with this information, fire up a small PHP script along the following lines :

require_once 'app/Mage.php';
Mage::app();
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);

First we hook into Magento in the usual way - the first line assumes that the script will be saved to the web root of your site.

$fp = fopen('colours.csv', 'w');
$header = array("Colour");
fputcsv($fp, $header);

In this example we're exporting the 'colour' attribute, so we're creating a simple CSV file to hold the export called colours.csv, creating the header row, and writing it to the CSV file.

$attribute = Mage::getSingleton('eav/config')->getAttribute(Mage_Catalog_Model_Product::ENTITY, 'color');

Note that the default colour attribute code is set to the American spelling of 'color' so this should be reflected in your script accordingly.

$options = $attribute->getSource()->getAllOptions(false);

We've now loaded the attribute into $attribute, and its options are now loaded into $options, so we need to loop through each one and retrieve the label. For each one, we put the label into an array then add that array as a new line to the CSV file.

foreach($options as $option) {
	$data = array($option['label'],"");
	fputcsv($fp,$data);
}

Finally we need to close off the CSV file.

fclose($fp);

That's it!

Author : Giles Bennett

About the author

Giles Bennett built his first website in 1996, and is old enough to miss Netscape Navigator. Initially a lawyer, he jumped ship to IT in 2008, and after 5 years as a freelancer, he founded HummingbirdUK in 2013. He can be reached by email at giles@hummingbirduk.com.