CSV File To DB In Yii

CSV File Upload

Using the below code i created the form “importcsvform.php”.

importcsvform

<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
 'id'=>'csv-form',
 'enableAjaxValidation'=>false,
    'htmlOptions'=>array('enctype' => 'multipart/form-data'),
)); ?>

 <?php //echo $form->errorSummary($model); ?>

 <div class="row">
  <?php echo $form->labelEx($model,'csvfile'); ?>
        <?php 
            $this->widget('CMultiFileUpload', array(
                'model'=>$model,
                'name' => 'csvfile',
                'max'=>1,
                'accept' => 'csv',
                'duplicate' => 'Duplicate file!', 
                'denied' => 'Invalid file type',              
            ));
        ?>
  <?php echo $form->error($model,'csvfile'); ?>
 </div>

 <div class="row buttons">
  <?php echo CHtml::submitButton('Import',array("id"=>"Import",'name'=>'Import')); ?>
 </div>
<?php $this->endWidget(); ?>
</div><!-- form -->

Read CSV In Controller

CSV file contains the data in follwoing format

Name Age
Yii 20
Framework 25
 public function actionImport(){
        $model=new Csv;
  if(isset($_POST['csv']))
  {
   $model->attributes=$_POST['csv'];
            $filelist=CUploadedFile::getInstancesByName('csvfile');
   // To validate 
            if($filelist)
                $model->csvfile=1;
            if($model->validate())
            {
                foreach($filelist as $file)
                {
                    try{
                    $transaction = Yii::app()->db->beginTransaction();
                    $handle = fopen("$file->tempName", "r");
                    $row = 1;
                    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                        if($row>1){
                              $newmodel=new Csv;       
                              $newmodel->name=$data[0];
                              $newmodel->age=$data[1];
                              $newmodel->save();            
                        }
                        $row++;               
                    }
                    $transaction->commit();
                    }catch(Exception $error){
                        print_r($error);
                        $transaction->rollback();
                    }                    
                }                            
            }                        
  }
  $this->render('importcsvform',array(
   'model'=>$model,
  ));        
    }

Leave a Reply

Your email address will not be published. Required fields are marked *