Creating CSV files in Magento

There are many tools in Magento which allow you to view or generate and download different reports. So, we can conclude that Magento system has integrated tools for CSV and XML files generation. It might help in the situation when you need to generate a report for some feed or just export a list of structured data. We would like to demonstrate the small example that adds an ability to generate and download CSV files.
Let’s assume that you have already created your custom extension and wish to add a CSV export functionality. If it’s not the case and you can’t guess how to create an extension, then you can always find the light in our previous articles, for example this one. We called our extension Atwix_Tweaks so in the code examples below we will use this title.

As we said before, the file is being downloaded within some URL. Well, then we need to create the controller and corresponded method-action. In config.xml file add the section which will tell the system where our controller is located:


On the next step, we should create the controller itself (app/code/local/Atwix/Tweaks/controllers/IndexController.php):

class Atwix_Tweaks_IndexController extends Mage_Core_Controller_Front_Action
     * Returns generated CSV file
    public function mlnProductsListAction()
        $filename = 'mln.csv';
        $content = Mage::helper('atwix_tweaks/mln')->generateMlnList();

        $this->_prepareDownloadResponse($filename, $content);

As you can see, the controller calls method generateMlnList() from helper ‘atwix_tweaks/mln’. What are we going to do next? Right, create the helper (app/code/local/Atwix/Tweaks/Helper/Mln.php):

class Atwix_Tweaks_Helper_Mln extends Mage_Core_Helper_Abstract
     * Contains current collection
     * @var string
    protected $_list = null;

    public function __construct()
        $collection = Mage::getModel('catalog/product')->getCollection()
            ->addAttributeToFilter(array('attribute' => 'wight', 'gt' => 2));


     * Sets current collection
     * @param $query
    public function setList($collection)
        $this->_list = $collection;

     * Returns indexes of the fetched array as headers for CSV
     * @param array $products
     * @return array
    protected function _getCsvHeaders($products)
        $product = current($products);
        $headers = array_keys($product->getData());

        return $headers;

     * Generates CSV file with product's list according to the collection in the $this->_list
     * @return array
    public function generateMlnList()
        if (!is_null($this->_list)) {
            $items = $this->_list->getItems();
            if (count($items) > 0) {

                $io = new Varien_Io_File();
                $path = Mage::getBaseDir('var') . DS . 'export' . DS;
                $name = md5(microtime());
                $file = $path . DS . $name . '.csv';
                $io->open(array('path' => $path));
                $io->streamOpen($file, 'w+');

                foreach ($items as $product) {

                return array(
                    'type'  => 'filename',
                    'value' => $file,
                    'rm'    => true // can delete file after use

The helper uses Varien_Io_File class, integrated in Magento, to generate a custom CSV file. Generated file will be stored in the media folder and deleted before the controller sends header to the client side. If you don’t want to delete file, you can set parameter rm to false in the return statement. In the constructor (method __construct) you can use any collection you want (customers, orders, custom collections etc.). Also, you are able to pass the collection behind the constructor using method setList().
I hope this small example will help you in your further development. If you have some suggestions or questions you can always place them here ⇩ :)

You may also want to read:


Smart Brands Choose Us.

From Mark Cuban and Sir Richard Branson backed startups, to Inc 500 US Fastest Growing Companies and Global Brands choose us to deliver and support unparalleled eСommerce experience for their customers.