LoginSignup
27
33

More than 5 years have passed since last update.

基礎:PHPでDBからCSVを出力する(簡易版)

Last updated at Posted at 2017-07-03

はじめに

要件定義でお客さんと話していて必ず話に上がるCSV出力ですが、
実際に実装する機会がなかったので、1時間程度で簡単に実装してみました。
また、実装してみてちゃんとまとまったURLがなかったのもあり備忘録とします。

動作環境

MAC OS
MAMP(Apache, MySQL)

実装

step1: DB接続のための情報を定義する

    /*
      define database connection
     */
     $dbname = "treat_csv"; //データベース名

     $dsn = "mysql:dbname={$dbname};host={$dbhost}";
     $dbuser = "root"; //データベースユーザー名
     $dbpassword = "root"; //データベースユーザーパスワード

PDOクラスを利用してDBにアクセスするための情報を定義

step2: CSVのファイル名・ヘッダー名を定義

    /*
      define csv file information
    */
    $file_path = "customer.csv"; //ファイル名
    $export_csv_title = ["顧客ID", "名前", "性別", "電話番号"]; //ヘッダー項目
    $export_sql = "SELECT id, name, sex, tel FROM customers"; //SQL文

上記の定義をした後、ヘッダーの文字コードをSJIS-winにエンコードします。
SJISでカバーしていない難しい漢字等の対応のために行います。

    // encoding title into SJIS-win
    foreach( $export_csv_title as $key => $val ){

        $export_header[] = mb_convert_encoding($val, 'SJIS-win', 'UTF-8');
    }

step3: データベースに接続する。

    /*
      Create Database Connection
     */
    try{
        $dbh = new PDO($dsn, $dbuser, $dbpassword);
    }catch(PDOException $e){
        print('Connection failed:'.$e->getMessage());
        die();
    }

step4: CSV書き込み出力

if(touch($file_path)){
        $file = new SplFileObject($file_path, "w");

        // 出力するCSVにヘッダーを書き込む
        $file->fputcsv($export_header);

        // データベース検索
        $stmt = $dbh->query($export_sql);

        // 検索結果をCSVに書き込む(SJIS-winに変換するコードに後々更新します。)
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            $file->fputcsv($row);

        }

        // データベース接続の切断
        $dbh = null;
    }

以上です。

ソースコード全体

<?php
    /*
      define database connection
     */
     $dbname = "treat_csv";

     $dsn = "mysql:dbname={$dbname};host={$dbhost}";
     $dbuser = "root";
     $dbpassword = "root";

    /*
      define csv file information
    */
    $file_path = "customer.csv";
    $export_csv_title = ["顧客ID", "名前", "性別", "電話番号"];
    $export_sql = "SELECT id, name, sex, tel FROM customers";

    /*
      Create Database Connection
     */
    try{
        $dbh = new PDO($dsn, $dbuser, $dbpassword);
    }catch(PDOException $e){
        print('Connection failed:'.$e->getMessage());
        die();
    }

    // encoding title into SJIS-win
    foreach( $export_csv_title as $key => $val ){

        $export_header[] = mb_convert_encoding($val, 'SJIS-win', 'UTF-8');
    }
    /*
        Make CSV content
     */
    if(touch($file_path)){
        $file = new SplFileObject($file_path, "w");

        // write csv header
        $file->fputcsv($export_header);

        // query database
        $stmt = $dbh->query($export_sql);

        // create csv sentences
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            $file->fputcsv($row);

        }

        // close database connection
        $dbh = null;
    }

github URL

https://github.com/KAZUKI1994/treat_csv

参考URL

27
33
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
27
33