2

I am creating csv exporter for some custom tables where multiple tables are combined in a way that is not like any model or grid in the back end. In the controller I have a action function that collects the data and combines it into a 2 dimensional array. I am currently trying to refine the function that converts the array into a string for _prepareDownloadResponse and am wondering if it can be used together with Varien_File_Csv to convert an array to a csv.

I know the following works, though some extra processing is needed around the implode.

$csv_data = array();

// Add data to $csv_data

$fileName = "example.csv";

$content = "";
foreach($csv_data as $line){
  $content .= implode(",", $line)."\n";
}

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

I am wondering if the following is possible

$csv_data = array();

// Add data to $csv_data

$fileName = "example.csv";

$var_csv = new Varien_File_Csv();

$var_csv->saveData($fileName, $csv_data);

// a step here is need to get the string out of the file into $content

$this->_prepareDownloadResponse($fileName, $content);
3

You can do it like that, although I do not think that it is better than your first solution:

$csv_data = array();

// Add data to $csv_data

$fileName = "example.csv";

$var_csv = new Varien_File_Csv();

$var_csv->saveData($fileName, $csv_data);

$this->_prepareDownloadResponse($fileName, array('type' => 'filename', 'value' => $fileName));

This will write the CSV data to a file (saveData()), will read it from there and will prepare a download response for it (_prepareDownloadResponse). Sine there is a file write and file read here, I think it is better to use your first code, which does not need that and which is therefore probably faster.

  • this is the code : justpaste.it/1g31g how can i download into var->export folder – zus Jan 23 '18 at 10:26
0

This is possible. See this guide.

Basically:

$file = 'example.csv';
$csv = new Varien_File_Csv();
$csvdata = array();
$products = Mage::getModel('catalog/product')->getCollection();

foreach ($products as $product)
{
    $product_data = array();
    $product_data['id'] = $product->getId();
    $product_data['sku'] = $product->getSku();

    $csvdata[] = $product_data;
}

$csv->saveData($file, $csvdata);
0

As an easy approach you can create the csv file separately and then use the location of the file as URL to download the file.

    $file_url = file_location
    $downloadName = 'filename.csv';
    return $this->_prepareDownloadResponse($downloadName, array('type' => 'filename', 'value' => $file_url,'rm' => true));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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