title: php array to csv download integrated into my current script not working properly
body: <p>I've found several useful and helpful tutorials and forum posts on this subject. But none I could find display an exact example and implementation of my current scenario.</p>
  
  <p>I am trying to convert my completed query results array into csv format, so I can download the results, properly formatted, in .csv format.</p>
  
  <p>Below is my code:</p>
  
  <p><strong>This is my download action:</strong></p>
  
  <pre><code>&lt;script&gt;
      function getcsv(){
      window.location="script_4.php";
  }
  &lt;/script&gt;
  &lt;input type="button" onclick="getcsv()" value="Download CSV"&gt;
  </code></pre>
  
  <p><strong>This is my while() loop merging my query data into a sequential numeric array:</strong></p>
  
  <pre><code>while ($row = mysql_fetch_row($result)) {
  $industries = explode(",", $row[3]);
  unset($row[3]);
  $merge = array_merge($row, $industries);
  echo "&lt;pre&gt;";
  print_r($merge);
  echo "&lt;/pre&gt;";
  }
  </code></pre>
  
  <p><strong>My print_r() above echoes out like this:</strong></p>
  
  <pre><code>Array
  (
      [0] =&gt; 3561
      [1] =&gt; The Ace Company
      [2] =&gt; ace@not-a-real-site.com
      [3] =&gt; Waterproofing
  )
  Array
  (
      [0] =&gt; 3562
      [1] =&gt; JOJO Associates, Inc.
      [2] =&gt; joj@not-a-real-site.com
      [3] =&gt; Lab Equipment &amp; Casework
  )
  Array
  (
      [0] =&gt; 3564
      [1] =&gt; Southern Style Pipe
      [2] =&gt; southern@no-a-real-site.com
      [3] =&gt; Plumbing
      [4] =&gt; Piping
      [5] =&gt; Pipe Inspection
  )
  </code></pre>
  
  <p><strong>This is where I am at with the download script, and when I attempt it it loads my html and entire array into the csv with no csv formatting of array data.</strong></p>
  
  <pre><code>header("Content-type: text/csv");
  header("Content-Disposition: attachment; filename=file.csv");
  header("Pragma: no-cache");
  header("Expires: 0");
  
  outputCSV($merge);
  
  function outputCSV($data) {
      $outstream = fopen("php://output", "w");
      function __outputCSV(&amp;$vals, $key, $filehandler) {
          fputcsv($filehandler, $vals);
      }
      array_walk($data, "__outputCSV", $outstream);
      fclose($outstream);
  }
  </code></pre>