Hello All,
You might have seen that Magento provides a functionality to directly export the content from the grids in most of the modules seen in admin end like Sales, Products etc in the form of CSV or XML.
Sometimes the need arises to generate a CSV with the custom data.
Magento has already a nice class for it, it can be found at lib/Varien/File file name Csv.php. This class can be used to read and write CSV.
I am listing here a sample code for it.
<?php $file_path = '/your_dir_path/sample.csv'; //file path of the CSV file in which the data to be saved $mage_csv = new Varien_File_Csv(); //mage CSV $products_ids = array(1,2,3); //product ids whose data to be written $products_model = Mage::getModel('catalog/product'); //get products model $products_row = array(); foreach ($products_ids as $pid) { $prod = $products_model->load($pid); $data = array(); $data['sku'] = $prod->getSku(); $data['name'] = $prod->getName(); $data['price'] = $prod->getPrice(); $products_row[] = $data; } //write to csv file $mage_csv->saveData($file_path, $products_row); //note $products_row will be two dimensional array ?>
The above code will save the products data into the CSV file.
Hope this helps
can you give the complete example for those source code? because i copy and paste and then use the link doesn’t work. please help me you can’t reply this to my email
You can use the code in any file even the template file,
, you need to use the path (‘/your_dir_path/sample.csv’) as per your directory structure
Hi,
Good post. Can you please tell me how we can download this file.
Thanks
Create an
tag and give the location of the CSV generated in it, clicking this link will ask for download of CSV, or you can use PHP header functions for downloading directly from browser