title: Create .csv / text file in drupal
body: <p>What I want to do is exporting an SQL query to a .csv file so that it can be downloaded by the user. The query is more or less like this:</p>
  
  <pre><code>SELECT * FROM {registered} WHERE pending = 'Y'
  </code></pre>
  
  <p>I want the result of that query to be put in a .csv file and I also want the rows in questions to be updated with pending = 'N' and completed_time = NOW().</p>
  
  <p>I also want the headers to be included at the top.</p>
  
  <p>Is there any standard drupal functions that should be used or should I simply use the file_create_filename function and then create the file the normal php way?</p>
  
  <p>I tried doing like this:</p>
  
  <pre><code>// Save query data
  $result = db_query("SELECT *
                      INTO OUTFILE '/tmp/myfile-raw'
                      FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '\"'
                      LINES TERMINATED BY '\n'
                      FROM {plan_tax_red_registered}");
  
  if (!$result) {
    echo 'Failed saving query\n';
    return ;
  }
  
  $file = fopen("/tmp/myfile-raw","rw+");
  
  if (!$file) {
    echo 'Failed opening again\n';
    return ;
  }
  
  // Might be uneccessary but database fields can change
  $columns = db_query("SHOW FIELDS FROM {plan_tax_red_registered}");
  $list_of_columns = array();
  while ($res = db_fetch_array($columns)) {
    $list_of_columns[] = $res['Field'];
  }
  
  $header = implode(";", $list_of_columns);
  
  // Get the contents from the raw file
  $old_content = file_get_contents($file);
  
  // Save result
  $csv_file = fopen("/tmp/result.csv","rw+");
  
  if (!$csv_file) {
    echo "Failed opening csv file\n";
    return;
  }
  
  fwrite($csv_file, $header . "\n" . $old_content);
  
  fclose($file);
  
  fclose($csv_file);
  </code></pre>
  
  <p>Unfortunately, I couldn't open the csv file :(</p>
  
  <p>I know I could simply do this to show the file:</p>
  
  <pre><code>function plan_tax_red_export_to_excel($result,  $filename = 'myfile.csv'){
    drupal_set_header('Content-Type: text/csv');
    drupal_set_header('Content-Disposition: attachment; filename=' . $filename);
  
    $count = mysql_num_fields($result);
    for($i = 0; $i &lt; $count; $i++){
      $header[] = mysql_field_name($result, $i);
    }
    print implode(';', $header) ."\r\n";
  
    while($row = db_fetch_array($result)){
      foreach($row as $value){
        $values[] = '"' . str_replace('"', '""', decode_entities(strip_tags($value))) . '"';
      }
      print implode(';', $values) ."\r\n";
      unset($values);
    }
  }
  </code></pre>
  
  <p>But I want to update the content as well (setting the is_pending field to 'N' and completed_time to NOW()).</p>
  
  <p>What are your ideas? Any help is appreciated :)</p>
  
  <p>Kind regards,
  Samuel</p>