PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, January 20, 2022

[FIXED] Skip the first line of a CSV file in Yii2

 January 20, 2022     csv, phpmyadmin, yii-extensions, yii2     No comments   

Issue

public function actionUpload(){ $model = new CsvForm();

    if($model->load(Yii::$app->request->post())){
        $file = UploadedFile::getInstance($model,'file');
        $filename = 'Data.'.$file->extension;
        $upload = $file->saveAs('uploads/'.$filename);
        if($upload){
            define('CSV_PATH','uploads/');
            $csv_file = CSV_PATH . $filename;
            $filecsv = file($csv_file);
            print_r($filecsv);
            foreach($filecsv as $data){

                $modelnew = new Customer1();
                $hasil = explode(",",$data);
                $nim = $hasil[0];
                $nama = $hasil[1];
                $jurusan = $hasil[2];
                $angkatan = $hasil[3];

                $modelnew->username = $nim;
                $modelnew->firstname = $nama;
                $modelnew->lastname = $jurusan;
                $modelnew->password = $angkatan;

                $modelnew->save();
            }
            unlink('uploads/'.$filename);
            return $this->redirect(['site/index']);
        }
    }else{
        return $this->render('upload',['model'=>$model]);
    }
}

This is my CSV data

user1,name,pass,info user2,name,pass,info etc..,

So I want to skip Bold content and proceed my execution.


Solution

You could shift the array

$filecsvtemp = file($csv_file);
$filecsv = array_shift($filecsvtemp );

in this way the first row of the array is not present in the resulting array

otherwise use a counter

        $cnt = 0;
        $filecsv = file($csv_file);
        print_r($filecsv);
        foreach($filecsv as $data){

            if ($cnt!=0){
              $modelnew = new Customer1();
              $hasil = explode(",",$data);
              $nim = $hasil[0];
              $nama = $hasil[1];
              $jurusan = $hasil[2];
              $angkatan = $hasil[3];

              $modelnew->username = $nim;
              $modelnew->firstname = $nama;
              $modelnew->lastname = $jurusan;
              $modelnew->password = $angkatan;

              $modelnew->save();

            }
            $cnt++;
        }


Answered By - ScaisEdge
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing