Use Varien_File_Csv to import and export CSV files
Varien_File_Csv is a library which is used by Magento to manage files on csv format. This is pretty much simple working with csv’s with it.
To read a csv file you can do the following:
1 2 3 4 5 6 7 8 9 10 11 12 |
$filename = 'filename.csv'; $csvObject = new Varien_File_Csv(); $data = $csvObject->getData($filename); $csvObject->setDelimiter(';'); $csvObject->setEnclosure('"'); foreach ($data as $dataRow) { var_dump( $dataRow ); } |
To write a csv file you can do the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$filename = 'filename.csv'; $csvObject = 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; } $csvObject->setDelimiter(';'); $csvObject->setEnclosure('"'); $csvObject->saveData($file, $csvdata); |