简体   繁体   中英

Problems creating a .csv download

I am trying to create a .csv download from a mysql table without much success. I have put together the code below from a tutorial that I found here http://code.stephenmorley.org/php/creating-downloadable-csv-files/ but for some reason the .csv file that is downloaded contains the entire source code of the page not the column headings and data from the mysql table.

Any help would be much appreciated :)

    // output headers so that the file is downloaded rather than displayed
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=site-list-export.csv');

    // create a file pointer connected to the output stream
    $output = fopen('php://output', 'w');

    // output the column headings
    fputcsv($output, array('id', 'url', 'clean_host', 'keyword', 'group', 'page_number', 'page_authority', 'domain_authority', 'page_mozrank', 'seomoz', 'page_title', 'check_inbound', 'check_inbound_priority ', 'count', 'project', 'type'));


    // fetch the data
    $connect = mysql_connect("localhost", DB_USERNAME, DB_PASSWORD);
    mysql_select_db(DB_DATABASE, $connect);

    $rows = mysql_query("SELECT * 
    FROM `url_list_google`
    WHERE `group` = '".$selected_group."' 
    GROUP BY clean_host 
    ORDER BY `domain_authority` DESC") or die(mysql_error());
    mysql_close($connect);

    // loop over the rows, outputting them
    while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);

    }

Add exit; function call after your loop and it will prevent else content rendering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM