LoginSignup
0
0

More than 1 year has passed since last update.

銀行api 作成 01。 PHPでcsvをエクスポートして、データベースへ挿入 3,8000件

Posted at

●銀行のcsvデータは、【銀行コード フリーデータ】などで検索しますと、ダウンロードができるサイトがいくつかでてきます。

●データレイアウト
スクリーンショット (683).png

※支店コードは別テーブル、別CSVで取得しています。

PHP index.php

<?php 


 // エラーを出力する
 ini_set('display_errors', "On");
 require (dirname(__FILE__) . '/functions.php');


 // *** エックスサーバー用 接続情報
 $dsn = 'サーバー情報';
 $user = 'サーバーのユーザー名';
 $password = 'サーバーのパスワード';

 // ====== CSV データ インポート ======
$idx = 0;
$arr_1 = [];
$arr_2 = [];
$arr_3 = [];
$arr_4 = [];
$arr_5 = [];

// ================== CSV ファイル import ===============

$csvfile = file_get_contents(dirname(__FILE__). '/ginkositen.csv');

$csv_utf8_file = mb_convert_encoding($csvfile, 'UTF-8', 'SJIS-win');

// ファイルに書き込む
file_put_contents(dirname(__FILE__) . '/utf8_ginkositen.csv', $csv_utf8_file);

$file_handler = fopen(dirname(__FILE__) .'/utf8_ginkositen.csv', "r");

try {

       // PDO オブジェクト作成
       $pdo = new PDO($dsn, $user, $password);

       // トランザクション開始

       $pdo->beginTransaction();
       $sql = "INSERT INTO test_01_table(
        bank_code, bank_num, bank_kana, bank_name, bank_item
    ) VALUES";

$idx = 0;
    // ========= CSVファイルを 1行ずつ ファイルに読み込む =========

while($data = fgetcsv($file_handler)) {

    $arr_1[$idx] = $data[0]; 
    $arr_2[$idx] = $data[1];
    $arr_3[$idx] = $data[2];
    $arr_4[$idx] = $data[3];
    $arr_5[$idx] = $data[4];

    // ===== 配列の最後の要素
if ($idx === 31237) {
   
    $sql .= "(:bank_code{$idx},:bank_num{$idx},:bank_kana{$idx},:bank_name{$idx},:bank_item{$idx})";

} else {
    
    $sql .= "(:bank_code{$idx},:bank_num{$idx},:bank_kana{$idx},:bank_name{$idx},:bank_item{$idx}),";

}

// var_dump($sql . "<br /><br />");
$idx += 1;

}

$stmt = $pdo->prepare($sql);

//======= バインド index 用 
$j = 0;

foreach($arr_1 as $arr1) {
    $stmt->bindValue(':bank_code' . (string)$j, $arr1, PDO::PARAM_STR);
    $stmt->bindValue(':bank_num' . (string)$j, $arr_2[$j], PDO::PARAM_STR);
    $stmt->bindValue(':bank_kana' . (string)$j, $arr_3[$j], PDO::PARAM_STR);
    $stmt->bindValue(':bank_name' . (string)$j, $arr_4[$j], PDO::PARAM_STR);
    $stmt->bindValue(':bank_item' . (string)$j, $arr_5[$j], PDO::PARAM_STR);

    $j += 1;
}

var_dump($stmt);

    // SQL 実行
    $res = $stmt->execute();

    var_dump($res);

    // ======= (トランザクション) コミット =========
     if( $res ) {
        $pdo->commit();
        print("コミットOK");
    } else {
        print("コミットNG");
    }

} catch(PDOException $e) {
    print('Error:'.$e->getMessage());

    // ======= (トランザクション) ロールバック =========
     $pdo->rollBack();

   } finally {
    $pdo = null;
}

?>
0
0
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
0
0