title: PHP Array to CSV
body: <p>I'm trying to convert an array of products into a CSV file, but it doesn't seem to be going to plan. The CSV file is one long line, here is my code: </p>
  
  <pre><code>for($i=0;$i&lt;count($prods);$i++) {
  $sql = "SELECT * FROM products WHERE id = '".$prods[$i]."'";
  $result = $mysqli-&gt;query($sql);
  $info = $result-&gt;fetch_array(); 
  }
  
  $header = '';
  
  for($i=0;$i&lt;count($info);$i++)  
    {
      $row = $info[$i];
  
      $line = '';
      for($b=0;$b&lt;count($row);$b++)
      { 
      $value = $row[$b];                                      
          if ( ( !isset( $value ) ) || ( $value == "" ) )
          {
              $value = "\t";
          }
          else
          {
              $value = str_replace( '"' , '""' , $value );
              $value = '"' . $value . '"' . "\t";
          }
           $line .= $value;
          }
      $data .= trim( $line ) . "\n";
  }
  $data = str_replace( "\r" , "" , $data );
  
  if ( $data == "" )
  {
  $data = "\n(0) Records Found!\n";                        
  }
  
  header("Content-type: application/octet-stream");
  header("Content-Disposition: attachment; filename=your_desired_name.xls");
  header("Pragma: no-cache");
  header("Expires: 0");
  
  array_to_CSV($data);
  
  
  function array_to_CSV($data)
      {
          $outstream = fopen("php://output", 'r+');
          fputcsv($outstream, $data, ',', '"');
          rewind($outstream);
          $csv = fgets($outstream);
          fclose($outstream);
          return $csv;
      }
  </code></pre>
  
  <p>Also, the header doesn't force a download. I've been copy and pasting the output and saving as .csv </p>
  
  <h2>EDIT</h2>
  
  <p>PROBLEM RESOLVED: </p>
  
  <p>If anyone else was looking for the same thing, found a better way of doing it:</p>
  
  <pre><code>$num = 0;
  $sql = "SELECT id, name, description FROM products";
  if($result = $mysqli-&gt;query($sql)) {
       while($p = $result-&gt;fetch_array()) {
           $prod[$num]['id']          = $p['id'];
           $prod[$num]['name']        = $p['name'];
           $prod[$num]['description'] = $p['description'];
           $num++;        
      }
   }
  $output = fopen("php://output",'w') or die("Can't open php://output");
  header("Content-Type:application/csv"); 
  header("Content-Disposition:attachment;filename=pressurecsv.csv"); 
  fputcsv($output, array('id','name','description'));
  foreach($prod as $product) {
      fputcsv($output, $product);
  }
  fclose($output) or die("Can't close php://output");
  </code></pre>