1

How to download csv in my local system....?

controller.php

public function exportmeAction(){
      try{
        $products = Mage::getModel("catalog/product")->getCollection();
        $products->addAttributeToSelect('category_ids');
        $products->addAttributeToSelect('*');
        $products->addAttributeToFilter('status', 1);//optional for only enabled products
        $products->addAttributeToFilter('visibility', 4)
        ->joinField('qty',
                         'cataloginventory/stock_item',
                         'qty',
                         'product_id=entity_id',
                         '{{table}}.stock_id=1',
                         'left');;//optional for products only visible in catalog and search
        $fp = fopen('exports.csv', 'w');
        $csvHeader = array("Product Id","Product Name","Product Sku","Product Url", "Product Image Url","Category Ids","Description","Product Qty","Special Price", "Price");
        fputcsv( $fp, $csvHeader,",");
        foreach ($products as $product){
            echo $sku = $product->getSku();
            echo $name = $product->getName();
            echo $id = $product->getId();
            echo $url = $product->getProductUrl();
            echo $des = $product->getDescription();
            echo $splprice = (int)$product->getFinalPrice();
            echo $price = (int)$product->getPrice();
            echo $qty = (int)$product->getQty();
            echo $img = Mage::helper('catalog/image')->init($product, 'image');
            echo $categoryIds = implode('|', $product->getCategoryIds());//change the category separator if needed
            fputcsv($fp, array($id, $name, $sku, $url, $img,$categoryIds,$des,$qty,$splprice,$price), ",");
        }
        fclose($fp);
      }

       catch (Exception $e) {
            echo 'Error Message: '.$e->getMessage();
      }
      $this->_redirectReferer();
      Mage::getSingleton('core/session')->addSuccess("Done");
   }

phtml

<form class="my-form" name="myForm" id="customize" action="<?php echo $this->getUrl('productexport/index/exportme');?>" method="post">

<div class="submit"><input type="submit" value="Customize" class="btn btn-default" /></div> 
</form>

i got this error

Cannot send headers; headers already sent in C:\xampp\htdocs\test\app\code\local\MPS\Productexport\controllers\IndexController.php, line 48

Also i want to download in my local system how to achieve this?

2
  • remove echo with in for each loop and why you are not using magento built in function to create a csv and download it Jan 30, 2017 at 7:23
  • I want to download my local system. I don't want to all field. I want to custom
    – Magento 2
    Jan 30, 2017 at 7:27

3 Answers 3

1

you can use the Magento functions and change it as you want use below code

public function exportmeAction()
{

    $productCount = 0;
    try {
        //configure the collection filters.
        $collection = Mage::getResourceModel('catalog/product_collection')
            ->addAttributeToSelect('*');

        //Add a page size to the result set.
        $collection->setPageSize(100);
        //discover how many page the result will be.
        $pages = $collection->getLastPageNumber();
        $currentPage = 1;
        //This is the file to append the output to.
        $io = new Varien_Io_File();
        $path = Mage::getBaseDir('var') . DS . 'export' . DS;
        $name = 'your_file_name';
        $file = $path . DS . $name . '.csv';
        $io->setAllowCreateFolders(true);
        $io->open(array('path' => $path));
        $io->streamOpen($file, 'w+');
        $io->streamLock(true);
        $csvHeader = array("Product Id", "Product Name", "Product Sku", "Product Url", "Product Image Url", "Category Ids", "Description", "Product Qty", "Special Price", "Price");
        $io->streamWriteCsv($csvHeader);
        $productArray = array();
        do {
            //Tell the collection which page to load.
            $collection->setCurPage($currentPage);
            $collection->load();
            foreach ($collection as $product) {
                //write the collection array as a CSV.
                unset($productArray);
                $sku = $product->getSku();
                $name = $product->getName();
                $id = $product->getId();
                $url = $product->getProductUrl();
                $des = $product->getDescription();
                $splprice = (int)$product->getFinalPrice();
                $price = (int)$product->getPrice();
                $qty = (int)$product->getQty();
                $img = Mage::helper('catalog/image')->init($product, 'image');
                $categoryIds = implode('|', $product->getCategoryIds());//change the category separator if needed

                $productArray = array($id, $name, $sku, $url, $img,$categoryIds,$des,$qty,$splprice,$price);
                $io->streamWriteCsv($productArray);

                $productCount++;
            }
            $currentPage++;
            //make the collection unload the data in memory so it will pick up the next page when load() is called.
            $collection->clear();
        } while ($currentPage <= $pages);

    } catch (Exception $e) {
        //$response['error'] = $e->getMessage();
        Mage::printException($e);
    }
    $file_array = array(
        'type'  => 'filename',
        'value' => $file,
        'rm'    => true // can delete file after use
    );
    $this->_prepareDownloadResponse("product_exp.csv", $file_array);

    Mage::getSingleton('core/session')->addSuccess("Done");

}

put name of your csv file in $name and check your var/export folder

12
  • hey i want to download in my local machine not on server folder
    – Magento 2
    Jan 30, 2017 at 7:43
  • check edited answer Jan 30, 2017 at 7:47
  • Still save only var/export folder also format is changed means all value arranged in same cell
    – Magento 2
    Jan 30, 2017 at 7:51
  • please check updated answer i test this function and i am able to download the file and the format is ok now Jan 30, 2017 at 8:30
  • Hey Now Download in my local system but no data in that csv
    – Magento 2
    Jan 30, 2017 at 8:56
0

The error you're getting is caused by the fact that you're using echo in your controller.

Here's an updated version of your code that will let you download the CSV locally

public function exportmeAction(){
      try{
        $products = Mage::getModel("catalog/product")->getCollection();
        $products->addAttributeToSelect('category_ids');
        $products->addAttributeToSelect('*');
        $products->addAttributeToFilter('status', 1);//optional for only enabled products
        $products->addAttributeToFilter('visibility', 4)
        ->joinField('qty',
                         'cataloginventory/stock_item',
                         'qty',
                         'product_id=entity_id',
                         '{{table}}.stock_id=1',
                         'left');;//optional for products only visible in catalog and search
        $content = '"Product Id","Product Name","Product Sku","Product Url", "Product Image Url","Category Ids","Description","Product Qty","Special Price", "Price"\n';
        foreach ($products as $product){
            $content .= $product->getSku() . ",";
            $content .= $product->getName() . ",";
            $content .= $product->getId() . ",";
            $content .= $product->getProductUrl() . ",";
            $content .= $product->getDescription() . ",";
            $content .= (int)$product->getFinalPrice() . ",";
            $content .= (int)$product->getPrice() . ",";
            $content .= (int)$product->getQty() . ",";
            $content .= (string)Mage::helper('catalog/image')->init($product, 'image') . ",";
            $content .= implode('|', $product->getCategoryIds()) . ",";//change the category separator if needed
            $content .= "\n";
        }
      }

       catch (Exception $e) {
            echo 'Error Message: '.$e->getMessage();
      }
      Mage::getSingleton('core/session')->addSuccess("Done");
      $this->_prepareDownloadResponse('export.csv', $content, 'text/csv');
   }
3
  • all content showing single column only
    – Magento 2
    Jan 30, 2017 at 16:45
  • @Kothari try to set the delimiter as a comma and that'll work ;) Jan 30, 2017 at 16:50
  • how i can set delimiter as a comma
    – Magento 2
    Feb 2, 2017 at 18:52
0

this is the sctipt code to export all product it will helpful for you.

<?php
require_once('app/Mage.php');
Mage::app();

$data=array();
$data['entity'] = 'catalog_product';
$data['file_format'] = 'csv';
$data['form_key'] =Mage::getSingleton('core/session')->getFormKey(); 
$data['export_filter']=array();

$model = Mage::getModel('importexport/export');
$model->setData($data);

$model->export();
$model->getContentType();

?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.