Oftentimes, possibility of exporting significant amounts of data into CSV file format should be provided. Drupal Views has the Views data export module, that handles the majority of tasks for data export to CSV. However, this module cannot be used if we work with program generated pages. The following two simple functions can be used in such case: fopen() and fputcsv().

Let’s see how to return data as a file for loading on a server without saving.

Data is a list of nodes. In the first column we output machine names and in the second one - names.

First, we declare the route for downloading files using hook_menu().

function mymodule_menu() {
  $items = array();
  $items['dsta/download'] = array(
    'title' => t('Node types data export'),
    'page callback' => '_mymodule_download_data_callback',
    'access arguments' => TRUE,
    'type' => MENU_CALLBACK,
  );
 return $items;
}

The callback function implements the export logic.

function _mymodule_download_data_callback {
  //get all node types
  $types = node_type_get_types();
 
  //add necessary headers for browsers
  drupal_add_http_header('Content-Type', 'text/csv; utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename = nodes.csv');
 
  //instead of writing down to a file we write to the output stream
  $fh = fopen('php://output', 'w');
 
  //form header
  fputcsv($fh, array(t('Machine name'), t('Name')));
 
  //write data in the CSV format
  foreach ($types as $node_types) {
    fputcsv($fh, array($node_types->type, $node_types->name));
  }
 
  //close the stream
  fclose($fh);
}

Now, when users go through the /dsta/download link, they will be offered to save data as the CSV file.