'How to read content of CSV file in codeigniter

I have uploaded a CSV to codeigniter using a multipart-form, this is the HTML code:

<label for="enterCSV">Enter CSV            
<input  type="file"  name="enterCSV" accept=".csv">
</label>

and this is the php code on the controller:

  $csv = $_FILES['enterCSV']['name'];

            $file = fopen($csv, r); //open file
            while (!feof($file)){ //read till the end of the file
                $content = fgetcsv($file); //get content of the file
            }

I just want to read the content of the uploaded csv file using my php and manipulate it accordingly.



Solution 1:[1]

you can try this:

$csv = $_FILES['file']['tmp_name'];

$handle = fopen($csv,"r");
while (($row = fgetcsv($handle, 10000, ",")) != FALSE) //get row vales
{
    print_r($row); //rows in array

   //here you can manipulate the values by accessing the array


}

Solution 2:[2]

This is the code i used : on View :

<form action="<?php echo base_url('Controller/get_content'); ?>"  method="POST" enctype="multipart/form-data">
    <input type="file" class="custom-file-input" id="csv_file" name="csv_file"> 
    <label class="custom-file-label" for="csv_file">Choose CSV file</label>
    <button class="btn btn-success" type="submit"> Import</button>
</form>

On Controller :

public function get_content(){
    $csv = $_FILES['csv_file']['tmp_name'];
    $handle = fopen($csv,"r");
    while (($row = fgetcsv($handle, 10000, ",")) != FALSE)
    {
        //row should have same structure as database
        $add = $this->model->add($row);
    }
                
    redirect('/import_page', 'refresh');
}

On Model :

public function add($data){
   return $this->db->insert("table_csv", $data);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Madhu
Solution 2 Pierre Alexandre