title: export to csv wordpress
body: <p>I need to export data in one table in a csv file. I'm able to get the data fine but the CSV file is not being generated by the browser.</p>
  
  <p>My code is like this: its the problem with headers. I'm getting only the output with commas separated values but not getting csv file.</p>
  
  <pre><code>/* Converting data to CSV */
  
  public function CSV_GENERATE($getTable)
  {
      ob_clean();
      global $wpdb;
      $field='';
      $getField ='';
  
      if($getTable){
          $result = $wpdb-&gt;get_results("SELECT * FROM $getTable");
          $requestedTable = mysql_query("SELECT * FROM ".$getTable);
          // echo "hey";die;//var_dump($result);die;
  
          $fieldsCount = mysql_num_fields($requestedTable);
  
          for($i=0; $i&lt;$fieldsCount; $i++){
              $field = mysql_fetch_field($requestedTable);
              $field = (object) $field;         
              $getField .= $field-&gt;name.',';
          }
  
          $sub = substr_replace($getField, '', -1);
          $fields = $sub; # GET FIELDS NAME
          $each_field = explode(',', $sub);
          $csv_file_name = $getTable.'_'.date('Ymd_His').'.csv'; 
          # CSV FILE NAME WILL BE table_name_yyyymmdd_hhmmss.csv
  
          # GET FIELDS VALUES WITH LAST COMMA EXCLUDED
          foreach($result as $row){
              for($j = 0; $j &lt; $fieldsCount; $j++){
                  if($j == 0) $fields .= "\n"; # FORCE NEW LINE IF LOOP COMPLETE
                  $value = str_replace(array("\n", "\n\r", "\r\n", "\r"), "\t", $row-&gt;$each_field[$j]); # REPLACE NEW LINE WITH TAB
                  $value = str_getcsv ( $value , ",", "\"" , "\\"); # SEQUENCING DATA IN CSV FORMAT, REQUIRED PHP &gt;= 5.3.0
                  $fields .= $value[0].','; # SEPARATING FIELDS WITH COMMA
              }
              $fields = substr_replace($fields, '', -1); # REMOVE EXTRA SPACE AT STRING END
          }
  
          header("Content-type: text/x-csv"); # DECLARING FILE TYPE
          header("Content-Transfer-Encoding: binary");
          header("Content-Disposition: attachment; filename=".$csv_file_name); # EXPORT GENERATED CSV FILE
          header("Pragma: no-cache");
          header("Expires: 0"); 
          header("Content-type: application/x-msdownload");
          //header("Content-Disposition: attachment; filename=data.csv");
  
          return $fields; 
      }
  </code></pre>