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!