Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9098165
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T00:17:45+00:00 2026-06-17T00:17:45+00:00

I need to export data in one table in a csv file. I’m able

  • 0

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.

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.

/* Converting data to CSV */

public function CSV_GENERATE($getTable)
{
    ob_clean();
    global $wpdb;
    $field='';
    $getField ='';

    if($getTable){
        $result = $wpdb->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<$fieldsCount; $i++){
            $field = mysql_fetch_field($requestedTable);
            $field = (object) $field;         
            $getField .= $field->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 < $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->$each_field[$j]); # REPLACE NEW LINE WITH TAB
                $value = str_getcsv ( $value , ",", "\"" , "\\"); # SEQUENCING DATA IN CSV FORMAT, REQUIRED PHP >= 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; 
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T00:17:47+00:00Added an answer on June 17, 2026 at 12:17 am

    This is working perfectly now. we can use this as a plugin. I modified this post. thanks to sruthi sri.

    Hope this helps some one 🙂

    <?php
    
    class CSVExport
    {
    /**
    * Constructor
    */
    public function __construct()
    {
    if(isset($_GET['download_report']))
    {
    $csv = $this->generate_csv();
    
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private", false);
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"report.csv\";" );
    header("Content-Transfer-Encoding: binary");
    
    echo $csv;
    exit;
    }
    
    // Add extra menu items for admins
    add_action('admin_menu', array($this, 'admin_menu'));
    
    // Create end-points
    add_filter('query_vars', array($this, 'query_vars'));
    add_action('parse_request', array($this, 'parse_request'));
    }
    
    /**
    * Add extra menu items for admins
    */
    public function admin_menu()
    {
    add_menu_page('Download Report', 'Download Report', 'manage_options', 'download_report', array($this, 'download_report'));
    }
    
    /**
    * Allow for custom query variables
    */
    public function query_vars($query_vars)
    {
    $query_vars[] = 'download_report';
    return $query_vars;
    }
    
    /**
    * Parse the request
    */
    public function parse_request(&$wp)
    {
    if(array_key_exists('download_report', $wp->query_vars))
    {
    $this->download_report();
    exit;
    }
    }
    
    /**
    * Download report
    */
    public function download_report()
    {
    echo '<div class="wrap">';
    echo '<div id="icon-tools" class="icon32">
    </div>';
    echo '<h2>Download Report</h2>';
    //$url = site_url();
    
    echo '<p>Export the Subscribers';
    }
    
    /**
    * Converting data to CSV
    */
    public function generate_csv()
    {
    $csv_output = '';
    $table = 'users';
    
    $result = mysql_query("SHOW COLUMNS FROM ".$table."");
    
    $i = 0;
    if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
    $csv_output = $csv_output . $row['Field'].",";
    $i++;
    }
    }
    $csv_output .= "\n";
    
    $values = mysql_query("SELECT * FROM ".$table."");
    while ($rowr = mysql_fetch_row($values)) {
    for ($j=0;$j<$i;$j++) {
    $csv_output .= $rowr[$j].",";
    }
    $csv_output .= "\n";
    }
    
    return $csv_output;
    }
    }
    
    // Instantiate a singleton of this plugin
    $csvExport = new CSVExport();
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

What I need to do is export data into CSV file using T-SQL. And
I need to export data to a file from a huge table with only
I need to export some data from SAS to CSV, so that I can
being in need to export a DOC file to TXT and then reimport it
I need to export data from an existing TABLE. Till recently I used -
I need to export a table from phpmyadmin to a comma delimited text file.
A C# program I am working on will need to export data to one
I am trying to move data from one table into two new tables, but
I received a dbf file from one of our vendors. I need to export
I want users to be able to export data as an XML file. Of

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.