Skip to content

Instantly share code, notes, and snippets.

@leek
Forked from rmarscher/DownloadsController.php
Last active December 25, 2015 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leek/7020862 to your computer and use it in GitHub Desktop.
Save leek/7020862 to your computer and use it in GitHub Desktop.
<?php
namespace app\controllers;
use app\models\Downloads;
class DownloadsController extends \lithium\action\Controller {
public function index() {
$this->request->privateKeys = array('id', 'user_id');
// Dynamic conditions
$conditions = array(...);
$downloads = Downloads::find('all', array(
'fields' => array('user_id', 'Surveys.name'),
'conditions' => $conditions,
'with' => 'Surveys',
'order' => array('created' => 'desc')
));
return compact('downloads');
}
}
?>
<?php
// config/bootstrap/media.php
use lithium\util\Set;
use lithium\net\http\Media;
// Note: I did not need the "privateKeys" functionality so it has been removed.
Media::type('csv', 'application/csv', array(
'encode' => function($data, $handler, $response) {
// Assume first key is the one we are dumping
$data = reset($data);
// Write
ob_start();
$out = fopen('php://output', 'w');
foreach ($data as $record) {
$record = Set::flatten($record);
if (!isset($headers)) {
$headers = array_keys($record);
fputcsv($out, $headers);
}
fputcsv($out, $record);
}
fclose($out);
return ob_get_clean();
}
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment