Export CSV from Mysql

前端 未结 5 1026
伪装坚强ぢ
伪装坚强ぢ 2021-01-27 06:04

I\'m having a bit of trouble exporting a csv file that is created from one of my mysql tables using php.

The code I\'m using prints the correct data, but I can\'t see ho

5条回答
  •  暖寄归人
    2021-01-27 06:45

    Three things to consider:

    1. You're sending headers indicating that the user is going to be downloading a CSV file, but then you send create a link to download it? This isn't correct, you should be linking to this page, and then only outputting the CSV data itself after the headers.

    2. MySQL has the ability to generate CSV output, and you should definitely take advantage of this instead of trying to do it yourself. You can use SELECT INTO ... OUTFILE to do this.

    3. If you must create the CSV using PHP, please use fputcsv to do so. This will handle all the complications of CSV such as escaping and proper formatting. Since fputcsv writes to a file, you could either write it to a temporary file and then output it after you send your headers, or use the following trick to output it directly:

    Do this after sending headers:

    $fp = fopen('php://output', 'w');
    while( $row = mysql_fetch_row( $export ) ) {
        fputcsv($fp, $row);
    }
    

提交回复
热议问题