Created
September 16, 2012 13:38
-
-
Save oshiro-kazuma/3732499 to your computer and use it in GitHub Desktop.
PHPでCSVデータを生成
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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