Call our sales line
08000 484 679
Home > Magento Tips > Reading CSVs in Magento with Varien_File_Csv()

Reading CSVs in Magento with Varien_File_Csv()

Posted on: 31st Jan 2013 By: Adam Moss No Comments

The Varien library is full of useful classes which are used throughout the Magento application. One I came to use recently is Varien_File_Csv(). A class of useful methods for reading and updating CSV rows, and this is used many times in Magento as you can imagine with all the spreadsheet work we have to do!

If you go to lib/Varien/File/Csv.php you can take a look at the available methods. It’s not a huge class, but it does what’s needed.

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] );
}

Save CSVĀ - saveData()

To save 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. Thanks to Varien it’s as simple as that.

You can also change the delimiter, line length and separator values by using those methods as specified below. I can’t see why you’d ever need to do this though – by default CSVs are best comma separated and enclosed by double-quotes (so try not to change it).

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

Thanks for reading!

By Adam Moss

Adam is Ecommerce Manager and a PHP developer at Creare Group. Adam is responsible for training Magento development within the company. Follow Adam on Twitter: http://twitter.com/adampmoss. - .

Post A Comment

Your comments:
Enclose code snippets within the appropriate tags: [php][/php]   [js][/js]   [xml][/xml]   [css][/css]   [html][/html]
E.g: [php]<?php echo "hello world"; ?>[/php]

Search Blog

Follow us on Twitter

Archives

For the record...

Views & opinions in this blog are those of the individual and do not necessarily reflect those of E-commerce Web Design or the Creare Group.