Using Varien_File_Csv with Magento

The Varien library that runs alongside Zend is full of useful classes which are used throughout Magento. One of which is Varien_File_Csv which is created specifically for reading and writing to CSV files.

From your Magento root, go to lib/Varien/File/Csv.php and take a look at the class and its methods.

Read CSV – getData()

To read a CSV file create a new instance of the Varien_File_Csv class and pass your CSV file path into the getData() method.

$file = 'example.csv';
$csv = new Varien_File_Csv();
$data = $csv->getData($file);

for($i=1; $i<count($data); $i++)
{
	var_dump( $data[$i] );
}

Write to CSV – saveData()

To write data to a CSV is basically the opposite of what’s above. Using your CSV object call the method saveData() and pass in your file path and array. Your array needs to be 2-dimensional (i.e. an array of arrays).

$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);

In this example I’m simply adding rows of product data to my spreadsheet.

You can also change the delimiter, line length and separator values by using those methods as specified below. By default CSVs are most widely-read as comma separated and enclosed by double-quotes (so there’s not much need to change it).

$csv->setLineLength(1000);
$csv->setDelimiter(',');
$csv->setEnclosure('"');