Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We're retiring the forums!

The SilverStripe forums have passed their heyday. They'll stick around, but will be read only. We'd encourage you to get involved in the community via the following channels instead:

Archive /

Our old forums are still available as a read-only archive.

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo

outputting a table as csv

Go to End

2 Posts   2290 Views


Forum Moderator, 224 Posts

3 December 2007 at 9:21pm


Today I had one of these moments, where I really enjoyed using silverstripe... I used simple php and it seemed to work seemlessly with silverstripe.

I added the following function to a page controller:

function ExportDetails() {
if(Permission::check('ADMIN')) {
$result = mysql_query("SHOW COLUMNS FROM Mytable");
$select = 'SELECT ';
while($row = mysql_fetch_array($result)) {
$out .= $row["Field"].", ";
$select .= $row["Field"].", ";
$rowFieldNames[] = $row["Field"];
$out .= "ID\r\n";
$select .= " ID FROM Mytable";
$result = mysql_query($select);
while($dataRow = mysql_fetch_array($result)) {
foreach($rowFieldNames as $key=>$value) {
$out .= ''.str_replace(",", "[comma]", $dataRow[$value]).', ';
$out .= $row["ID"]."\r\n";
header("Content-Type: application/txt");
HTTPResponse::addHeader("Content-disposition", "RegistrationsOn".date("Y-m-d").".csv");
print $out;
else {
Security::permissionFailure($this, 'You must be logged in.');

and all I had to do is to add "ExportDetails" after the url and it works (e.g. mypage/ExportDetails gives the csv output. The only line that does not work is HTTPResponse::addHeader("Content-disposition", "RegistrationsOn".date("Y-m-d").".csv"); - it gives ExportDetails as filename. How can I change this.

I also still have to use the dataobject to retrieve the data rather than good old mysql_query (I just love writing my own sql).

Thank you



Forum Moderator, 922 Posts

3 December 2007 at 9:56pm

Edited: 03/12/2007 10:04pm

Hi there,

If you're using a TableListField, or a sub-class of, you can use something like this:

$table = new TableListField();

... // do stuff

$table->setPermissions(array('export', 'delete', 'print'));

'export' allows CSV exports out of the box in TableListField and sub-classes.

For more information, see the documentation for it here: