Generate a CSV file

Categories:

Generate a CSV file

Snippet to generate a CSV file from any table or combination of tables from the data base.

<?php
function csvWriter(){

   
// set the content as octet-stream
   
drupal_set_header("Content-Type: application/octet-stream");
   
// tell the thing the filesize
   
drupal_set_header("Content-Length: ".filesize("download.csv"));
   
// set it as an attachment and give a file name
   
drupal_set_header('Content-Disposition: attachment; filename="download.csv"');
   
   
   
$fp = fopen('download.csv', 'w');
       
       
// these are the headers of the columns
   
$csvFile = 'Title'.chr(13);

       
// modify the query to pull the info you need from the database here
   
$result = db_query("SELECT n.nid FROM node n WHERE n.type = 'my_content' " );

    while(
$element = db_fetch_object($result)){
       
$node = node_load($element->nid);
       
$csvFile .= str_replace(',','',$node->title).chr(13);
    }
   
   
fwrite($fp,$csvFile);
   
fclose($fp);

   
// read into the buffer
   
readfile("download.csv");
    exit;


}

csvWriter();

?>

I this example you will get a spread sheet with only the titles of the nodes that are "my_content" type.

Just make your modifications and insert this snippet into a page or any node. once you load the node, you will get prompted to download the CSV file.

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
2 + 9 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.