CodeIgniter3

21. [CodeIgniter3] CSV데이터를 MySQL로 가져오기

drizzle0925 2022. 1. 6. 09:42
728x90

CSV 기능을 사용한 대량 데이터 가져오기 기능은 웹 응용 프로그램 개발에 매우 유용한 기능입니다.

이 가져오기 기능은 대량 데이터를 하나씩 삽입하지 않고 한 번에 삽입하는데 도움이 되므로 데이터베이스에 데이터를 삽입하는 시간을 줄일 수 있습니다.

 

CodeIgniter 프레임워크에서 CSV 데이터를 지원하는 별도의 라이브러리는 없습니다.

그래서 사용자 만든 코드를 라이브러리화 해서 사용해야 합니다.

(다른 사람의 코드를 사용해도 좋고 본인의 코드를 사용해도 좋습니다.)

 

이 포스팅을 통해 CodeIgniter에서 CSV 파일 데이터를 MySQL 데이터베이스로 가져오는 방법을 보여 드리겠습니다.

 

Database

아래 쿼리를 이용하여 `tbl_user` 테이블을 생성합니다.

CREATE TABLE IF NOT EXISTS `tbl_user`(
	id int not null primary key auto_increment,
    name varchar(25) not null,
    phone varchar(30) not null,
    email varchar(200) not null
);

 

 

library

application/libraries/CSVReader.php 파일을 만들고 아래 코드를 입력합니다. (사용자 라이브러리입니다.)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * CSV Reader for CodeIgniter 3.x
 *
 * Library to read the CSV file. It helps to import a CSV file
 * and convert CSV data into an associative array.
 *
 * This library treats the first row of a CSV file
 * as a column header row.
 *
 *
 * @package     CodeIgniter
 * @category    Libraries
 * @author      CodexWorld
 * @license     http://www.codexworld.com/license/
 * @link        http://www.codexworld.com
 * @version     3.0
 */
class CSVReader {
    
    // Columns names after parsing
    private $fields;
    // Separator used to explode each line
    private $separator = ';';
    // Enclosure used to decorate each field
    private $enclosure = '"';
    // Maximum row size to be used for decoding
    private $max_row_size = 4096;
    
    /**
     * Parse a CSV file and returns as an array.
     *
     * @access    public
     * @param    filepath    string    Location of the CSV file
     *
     * @return mixed|boolean
     */
    function parse_csv($filepath){
        
        // If file doesn't exist, return false
        if(!file_exists($filepath)){
            return FALSE;            
        }
        
        // Open uploaded CSV file with read-only mode
        $csvFile = fopen($filepath, 'r');
        
        // Get Fields and values
        $this->fields = fgetcsv($csvFile, $this->max_row_size, $this->separator, $this->enclosure);
        $keys_values = explode(',', $this->fields[0]);
        $keys = $this->escape_string($keys_values);
        
        // Store CSV data in an array
        $csvData = array();
        $i = 1;
        while(($row = fgetcsv($csvFile, $this->max_row_size, $this->separator, $this->enclosure)) !== FALSE){
            // Skip empty lines
            if($row != NULL){
                $values = explode(',', $row[0]);
                if(count($keys) == count($values)){
                    $arr        = array();
                    $new_values = array();
                    $new_values = $this->escape_string($values);
                    for($j = 0; $j < count($keys); $j++){
                        if($keys[$j] != ""){
                            $arr[$keys[$j]] = $new_values[$j];
                        }
                    }
                    $csvData[$i] = $arr;
                    $i++;
                }
            }
        }
        // Close opened CSV file
        fclose($csvFile);
        
        return $csvData;
    }

    function escape_string($data){
        $result = array();
        foreach($data as $row){
            $result[] = str_replace('"', '', $row);
        }
        return $result;
    }   
}

 

 

Controller

application/controllers/Csv_import.php 파일을 만들고 아래 코드를 입력합니다.

<?php 
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Csv_import extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        // csv_import_model 호출
        $this->load->model('csv_import_model');

        // CSVReader 라이브러리 호출
        $this->load->library('CSVReader');
    }

    public function index()
    {
        $this->load->view('csv_import');
    }

    public function display_data()
    {
        $result = $this->csv_import_model->select();
        $output = '
            <h3 align="center">CSV에서 가져온 사용자 세부 정보</h3>
                <div class="table table-bordered">
                    <table class="table table-bordered table-striped">
                        <tr>
                            <th>No</th>
                            <th>이름</th>
                            <th>이메일</th>
                            <th>모바일</th>
                        </tr>
        ';
        $count = 0;
        if($result->num_rows() > 0)
        {
            foreach($result->result() as $row)
            {
                $count = $count + 1;
                $output .= '
                    <tr>
                        <td>'.$count.'</td>
                        <td>'.$row->name.'</td>
                        <td>'.$row->email.'</td>
                        <td>'.$row->phone.'</td>
                    </tr>';
            }
        }
        else
        {
            $output .= '
                <tr>
                    <td colspan="5" align="center">사용가능한 데이터가 없습니다.</td>
                </tr>
            ';
        }
        $output .= '</table></div>';
        echo $output;
    }

    public function import_csv()
    {
        $file_data = $this->csvreader->parse_csv($_FILES["csv_file"]["tmp_name"]);
        foreach($file_data as $row)
        {
            $data[] = array(
                'name' => $row['name'],
                'phone' => $row['phone'],
                'email' => $row['email']
            );
        }
        $this->csv_import_model->insert($data);
    }
}
?>

 

Model

application/models/Csv_import_model.php 파일을 만들고 아래 코드를 입력합니다.

<?php 
class Csv_import_model extends CI_Model
{
    public function select()
    {
        $this->db->order_by('id', 'DESC');
        $query = $this->db->get('tbl_user');
        return $query;
    }

    public function insert($data)
    {
        $this->db->insert_batch('tbl_user', $data);
    }
}
?>

 

 

view

application/views/csv_import.php 파일을 만들고 아래 코드를 입력합니다.

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeIgniter를 사용하여 CSV 데이터를 MySQL로 가져오기</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container box">
        <h3 align="center">CodeIgniter를 사용하여 CSV 데이터를 MySQL로 가져오기</h3>
        <form method="post" id="import_csv" enctype="multipart/form-data">
            <div class="form-group">
                <label>CSV 파일 선택</label>
                <input type="file" name="csv_file" id="csv_file" required accept=".csv" />
            </div>
            <br />
            <button type="submit" name="import_csv" class="btn btn-info" id="import_csv">CSV 가져오기</button>
        </form>
        <br />
        <div id="imported_csv_data"></div>
    </div>
    <script>
        $(document).ready(function(){
            // ajax로 data를 로드함
            load_data();

            function load_data()
            {
                $.ajax({
                    url: "<?php echo base_url(); ?>csv_import/display_data",
                    method: "POST",
                    success: function(data)
                    {
                        $("#imported_csv_data").html(data);
                    }
                });
            }

            $("#import_csv").on("submit", function(event){
                event.preventDefault();
                $.ajax({
                    url: "<?php echo base_url(); ?>csv_import/import_csv",
                    method: "POST",
                    data: new FormData(this),
                    contentType: false,
                    cache: false,
                    processData: false,
                    beforeSend: function()
                    {
                        $("#import_csv_btn").html('Importing...');
                    },
                    success: function(data)
                    {
                        $("#import_csv")[0].reset();
                        $("#import_csv_btn").attr('disabled', false);
                        $("import_csv_btn").html('Import Done');
                        load_data();
                    }
                });
            });
        });
    </script>
</body>
</html>

 

 

아래 URL로 이동합니다.

localhost/csv_import/

 

document.csv 파일을 업로드합니다.

document.csv
0.00MB

 

CSV 가져오기 버튼을 클릭합니다.

 

 

Github : https://github.com/jun0925/study/commit/24ee2efd469195fd1989ab9534bae6c50c1b6d93

728x90