title: Add Column Headers To a CSV File With PHP
body: <p>I am trying to convert a php/mysql generated table into a downloadable csv file.  When a user enters search parameters, a call is made to a mysql table and results returned as table.</p>
  
  <p>I used the solution offered in this thread and it works fabulously:     <a href="https://stackoverflow.com/questions/217424/create-a-csv-file-for-a-user-in-php">Create a CSV File for a user in PHP</a></p>
  
  <p>I am able to allow users to save or view the results as a csv file.  the problem I am having is I'm not sure how to add column headers to the file.  For example, the results that are returned are in the following format:  $result[x]['office'], $result[x]['user'], etc..., but I also want to add column titles like "Office" and "User" so that anyone looking at the csv file immediately knows what the data means.</p>
  
  <p>This is the function that generates the csv file:</p>
  
  <pre><code>    header("Content-type: text/csv");
      header("Content-Disposition: attachment; filename=$file.csv");
      header("Pragma: no-cache");
      header("Expires: 0");
      outputCSV($data);
  
  function outputCSV($data) {
          $outstream = fopen("php://output", "a");
          function __outputCSV(&amp;$vals, $key, $filehandler) {
              fputcsv($filehandler, $vals); // add parameters if you want
          }
          array_walk($data, "__outputCSV", $outstream);
          fclose($outstream);
      }
  </code></pre>
  
  <p>I have tried creating the following function, and then calling it right before I call outputCSV, but it is not successful:</p>
  
  <pre><code>function create_file_header()
  {       
      $headers = 'Office, User, Tag, Value';
      $fp = fopen("php://output", "w");
      file_put_contents("$file.csv", $headers);
      fclose($fp);
  }
  </code></pre>
  
  <p>Any help is greatly appreciated.</p>