Created
November 27, 2012 01:30
-
-
Save k-holy/4151816 to your computer and use it in GitHub Desktop.
Volcanus_Csv(Writer+Reader)のサンプルSilex+PDO版
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 | |
require_once __DIR__ . '/../vendor/autoload.php'; | |
use Silex\Application; | |
use Symfony\Component\HttpFoundation\Request; | |
$app = new Application(); | |
$app->get('/logs/', function(Application $app, Request $request) { | |
$file = new \SplFileObject('php://temp', 'r+'); | |
$writer = new \Volcanus\Csv\Writer(array( | |
'inputEncoding' => 'UTF-8', | |
'outputEncoding' => 'SJIS', | |
'writeHeaderLine' => true, | |
'responseFilename' => 'accesslogs.csv', | |
)); | |
$writer->fields(array( | |
array('id' , 'アクセスログID'), | |
array('requested_at', 'アクセス日時'), | |
array('name' , '名前'), | |
array('user_agent' , 'UserAgent'), | |
array(function($item) { | |
return sprintf("[%d]\r\n%s", $item['id'], $item['name']); | |
}, 'フィールド加工サンプル'), | |
)); | |
$db_options = include __DIR__ . '/../doctrine.php'; | |
$dsn = sprintf('mysql:host=%s;dbname=%s;charset=%s', | |
$db_options['host'], | |
$db_options['dbname'], | |
$db_options['charset'] | |
); | |
$db = new \PDO($dsn, | |
$db_options['user'], | |
$db_options['password'], | |
array(\PDO::ATTR_EMULATE_PREPARES => false) | |
); | |
$statement = $db->query('SELECT id, requested_at, name, user_agent FROM accesslogs', \PDO::FETCH_ASSOC); | |
$writer->file = $file; | |
$writer->write($statement); | |
$csv = $writer->content(); | |
$reader = new \Volcanus\Csv\Reader(array( | |
'inputEncoding' => 'SJIS', | |
'outputEncoding' => 'UTF-8', | |
)); | |
$reader->appendFilter(function($item) use ($app, $reader) { | |
// 1件目はヘッダ行なので除外 | |
if ($reader->parsed === 1) { | |
return false; | |
} | |
return sprintf('<li>[%s] (%d)%s %s</li>', | |
$app->escape($item[1]), | |
$app->escape($item[0]), | |
$app->escape($item[2]), | |
$app->escape($item[3]) | |
); | |
}); | |
$reader->file = $file; | |
$content = <<< CONTENT | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<meta name="robots" content="noindex,nofollow" /> | |
<title>Volcanus_Csvのテスト@%s</title> | |
</head> | |
<body> | |
<h1>Volcanus\Csv\Writer::content()</h1> | |
<pre>%s</pre> | |
<hr /> | |
<h1>Volcanus\Csv\Reader::fetchAll()</h1> | |
<ul>%s</ul> | |
</body> | |
</html> | |
CONTENT; | |
return new Response(sprintf($content, | |
$app->escape($request->server->get('HTTP_HOST')), | |
$app->escape(mb_convert_encoding($csv, 'UTF-8', 'SJIS')), | |
implode("\n", $reader->fetchAll()) | |
)); | |
}); | |
$app->run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment