Created
October 14, 2013 04:38
-
-
Save rmarscher/6970845 to your computer and use it in GitHub Desktop.
Lithium PHP framework CSV media handler - blacklists data not intended for export. See StackOverflow question "How do you remove specific fields from all entities of a record set in Lithium?": http://stackoverflow.com/questions/17189664/how-do-you-remove-specific-fields-from-all-entities-of-a-record-set-in-lithium/17202455
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