-
-
Save christopheradams/11280055 to your computer and use it in GitHub Desktop.
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 | |
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'); | |
} | |
} | |
?> |
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
// config/bootstrap/media.php | |
Media::type('csv', 'application/csv', array( | |
'encode' => function($data, $handler, $response) { | |
$request = $handler['request']; | |
$privateKeys = null; | |
if ($request->privateKeys) { | |
$privateKeys = array_fill_keys($request->privateKeys, true); | |
} | |
// assuming your csv data is the first key in | |
// the template data and the first row keys names | |
// can be used as headers | |
$data = current($data); | |
$row = (array) current($data); | |
if ($privateKeys) { | |
$row = array_diff_key($row, $privateKeys); | |
} | |
$headers = array_keys($row); | |
ob_start(); | |
$out = fopen('php://output', 'w'); | |
fputcsv($out, $headers); | |
foreach ($data as $record) { | |
if (!is_array($record)) { | |
$record = (array) $record; | |
} | |
if ($privateKeys) { | |
$record = array_diff_key($record, $privateKeys); | |
} | |
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