3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

1万件のCSVを読み込ませるPHPコード雛形。

Last updated at Posted at 2022-09-06

1万件のCSVを読み込ませるPHPコード雛形です。

動作環境はPHP8系

  • Read_csv_class.php…CSV読み込みを行っているファイル(雛形です)。
  • index.php…ajaxを使用しRead_csv_class.phpを呼び出しているファイル
  • こちらのCSVダミーデータを改変して動作確認をしています。

※ fgetcsv($this->handle, null, ",");の箇所はバージョンより要確認!

追記:テーブルに保存するコードを新たに作りました。
1万件のCSVを読み込みテーブルに保存する雛形コード #PHPCode

Read_csv_class.php
<?php
//ini_set("display_errors","On");
session_start();

class Read_csv{
    var $max=10000;
    var $cnt=0;
    var $handle = null;
    /**
     * @param string $filename
     * @param int $cnt
     */
    public function __construct($filename="",$cnt=0)
    {
        $this->cnt = $cnt;
        $this->handle =  fopen($filename, "r");
        $_SESSION["offset"]?fseek($this->handle,$_SESSION["offset"]):$this->handle;
        if ( $this->handle !== FALSE) {
            $this->reader();
        }
    }
    /**
     * @return void
     */
    public function reader():void
    {
            $response = null;
            $data = fgetcsv($this->handle, null, ",");
            if($data !== FALSE) {
                $_SESSION["offset"] = ftell($this->handle);
                $response["data"] = $data;
                $response["cnt"] = $this->cnt>$this->max?0:($this->cnt + 1);
                print json_encode($response);
            }else{
                $_SESSION["offset"] = null;
                print "";
            }
    }
}

if (isset($_POST["csrf_token"])  && d_xss($_POST["csrf_token"]) === $_SESSION['csrf_token']) {
    $_SESSION["offset"] = (int)d_xss($_POST["reset_flag"])===1?null:d_xss($_SESSION["offset"]);
    $filename = d_xss($_POST["filename"]);
    $cnt = (int)d_xss($_POST["cnt"]);
    //👉$Read_csv = new Read_csv($filename,$cnt);
    $Read_csv = null;
 }else{
    print "";
 }
 function d_xss($data){
    $data = strip_tags($data);
    $data = htmlspecialchars($data,ENT_QUOTES);
    return $data;
}

index.php
<?php
 // ログインした状態と同等にするためセッションを開始します
 session_start();
 // 暗号学的的に安全なランダムなバイナリを生成し、それを16進数に変換することでASCII文字列に変換します
  $toke_byte = openssl_random_pseudo_bytes(16);
  $csrf_token = bin2hex($toke_byte);
  // 生成したトークンをセッションに保存します
  $_SESSION['csrf_token'] = $csrf_token;
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="Description" content="Enter your description here"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<title>CSV</title>
</head>
<body>
    <input type="hidden" name="csrf_token" value="<?=$csrf_token?>">
    <span class="h3" id="cnt"></span><br><br>
    <span class="h4" id="read_csv"></span><br><br>
    <span class="h4" id="debug"></span><br><br>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script>
<script>
    window.onload = function(){
        read_csv(0,1);
    };
    function read_csv(cnt,reset_flag){
        try{
            $.ajax({
            type: "post",
            url: "./Read_csv_class.php",
            async: false,
            data: {csrf_token:document.getElementsByName("csrf_token")[0].value,reset_flag:reset_flag,filename:"dummy.csv",cnt:cnt},
            dataType: "json",
            success: function (response) {
                    if(response){
                        cnt = response.cnt;
                        document.getElementById("cnt").innerText = cnt;
                        document.getElementById("read_csv").innerText = response.data[0];
                        document.getElementById("debug").innerText = cnt ===21?response.data:document.getElementById("debug").innerText;
                        setTimeout(function(){read_csv(cnt)},0);
                    }
                }
            });
        }catch(e){
            console.warn(e);
            read_csv(cnt);
        }
    }
</script>
</body>
</html>

dummy.csv
SnapCrab_NoName_2022-9-7_5-46-59_No-00.png

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?