9/16/2011

How to upload and read csv file in magento

To upload CSV file and to read that file line by line , Please write the below code in magento

if(isset($_FILES['import_file']['name']) && $_FILES['import_file']['name'] != '')
{
    $uploaderFile = new Varien_File_Uploader('import_file');
    $uploaderFile->setAllowedExtensions(array());
    $uploaderFile->setAllowRenameFiles(false);
    $uploaderFile->setFilesDispersion(false);
    $uploaderFilepath = Mage::getBaseDir('media') . DS . 'importcsv' . DS ;
    $uploaderFile->save($uploaderFilepath, $_FILES['import_file']['name'] );
    $file = $_FILES['import_file']['name'];
    $filepath = $uploaderFilepath.$file;
    $i = 0;
    if(($handle = fopen("$filepath", "r")) !== FALSE) {
        while(($data = fgetcsv($handle, 1000, ",")) !== FALSE){            
            if($i>0 && count($data)>1){
                updateData($data);
            }          
            $i++;
        }
    }
    else{
        Mage::getSingleton('adminhtml/session')->addError("There is some Error");
        $this->_redirect('*/*/index');
    }
}
    function updateData($data)
    {
        //Write your code here and Update it to magento tables
    }

No comments:

Post a Comment