小金井にあるWEB制作会社の備忘録

MEMORANDUM

データベース(Mysql)に登録しているデータをCSV形式でダウンロード

管理画面からデータベース(Mysql)に登録している情報をCSV形式にしてダウンロードしたいという、要望があった際に実装した方法をメモ

PHP

$host = 'localhost'; // サーバー名
$sqlname = 'sample'; //データベース名
$username = 'xxxxx'; //データベースユーザー名
$pssword = 'xxxxx'; // パスワード
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND=>"SET CHARACTER SET 'utf8'");
$dbh = new PDO('mysql:host='.$host.';dbname='.$sqlname.'', $username, $pssword, $options);

// CSVファイル名の設定
$nowtime = date('Ymd', time());
$csv_file = 'CSV_'.$nowtime.'.csv';

// CSVデータの初期化
$csv_data = '';

// CSVデータの作成
$sql = $dbh->query('SELECT * FROM tbl_sample');
$csv_data .= mb_convert_encoding('項目名1, 項目名2, 項目名3, 項目名4, 項目名5', 'SJIS', 'UTF-8').'\n';
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
	$csv_data .= mb_convert_encoding($row['date01'], 'SJIS', 'UTF-8').','
	.mb_convert_encoding($row['date02'], 'SJIS', 'UTF-8').','
	.mb_convert_encoding($row['date03'], 'SJIS', 'UTF-8').','
	.mb_convert_encoding($row['date04'], 'SJIS', 'UTF-8').','
	.mb_convert_encoding($row['date05'], 'SJIS', 'UTF-8').'\n';
}
// MIMEタイプの設定
header('Content-Type: application/octet-stream');
// ファイル名の表示
header('Content-Disposition: attachment; filename=$csv_file');
// データの出力
echo($csv_data);

同一カテゴリーの記事