Skip to content

Instantly share code, notes, and snippets.

@oshiro-kazuma
Created September 16, 2012 13:38
Show Gist options
  • Save oshiro-kazuma/3732499 to your computer and use it in GitHub Desktop.
Save oshiro-kazuma/3732499 to your computer and use it in GitHub Desktop.
PHPでCSVデータを生成
<?php
// SilexとDoctrine使ってる感じで
$app->get('/csv/userlist/{id}.csv', function ($id) use ($app) {
// DBのデータを連想配列のリストで取得
$sql = "select * from user where result = 1 and groupid = ?";
$stmt = $app['db']->prepare($sql);
$stmt->bindValue(1, $id);
$stmt->execute();
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);
// ヘッダー生成
$csv = "";
foreach($items[0] as $key => $value) {
$keys[] = $key;
}
$csv = $csv. implode(',', $keys). PHP_EOL;
// CSVデータ出力
foreach($items as $item) {
$csv = $csv. implode(',', $item);
$csv = $csv. PHP_EOL;
}
// 一応Content-Typeも礼儀よく合わせて出力
return new Response(
$csv,
200,
array('Content-Type' => 'text/csv')
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment