Question

If a csv file with id, name, price columns reside in magento root dir

How I can read this file and retrieve data using Varien_File_Csv() from custom model?

Was it helpful?

Solution

You can use it in this way to get data from csv file:

public function getCsvData($file){
    $csvObject = new Varien_File_Csv();
    try {
        return $csvObject->getData($file);
    } catch (Exception $e) {
        Mage::log('Csv: ' . $file . ' - getCsvData() error - '. $e->getMessage(), Zend_Log::ERR, 'exception.log', true);
        return false;
    }

}

The $file variable contains the path to the csv file.

The loop to read the columns if $data is the result of the function above could be:

 foreach ($data as $lines => $line) {
            $rows[] = array(
                'column 1' => $line[0],
                'column 2' => $line[1],
                'column 3' => $line[2],
            );
  }

OTHER TIPS

This is for excel sheet, you can similarly do for csv.

<?php 
error_reporting(E_ALL | E_STRICT);
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
$app = Mage::app('default');

ini_set('display_errors', 1);

require_once 'reader.php';
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('CP1251');
$path='Book5.xls';
$data->read($path);

$alldata = $data->sheets[0]['cells'];

  $count=0;
foreach($alldata as $data){
      if($count!=0){
$simpleProduct = Mage::getModel('catalog/product')->loadByAttribute('sku',$data['1']);
if($simpleProduct) {
$simpleProduct->setMetaDescription($data['2']);
$simpleProduct->setMetaKeyword($data['3']);
$simpleProduct->setMetaTitle($data['4']);

$simpleProduct->save();
echo "Updated product " . $data['1']. "<br>";
}

Reader.php file you can doqnload for any Spreadsheet_Excel_Writer for php.

To read csv into array using column name as array keys, this worked for me - http://dltr.org/blog/magento/577/Magento-read-CSV-using-Varien_File_Csv-library

I found magento didn't have option to include first row as array keys, so ended up modifying like from above link myself and posted there on my magento blog.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top