Create a CSV File for a user in PHP

前端 未结 19 2038
故里飘歌
故里飘歌 2020-11-22 11:52

I have data in a MySQL database. I am sending the user a URL to get their data out as a CSV file.

I have the e-mailing of the link, MySQL query, etc. covered.

<
19条回答
  •  余生分开走
    2020-11-22 12:32

    Try:

    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=file.csv");
    header("Pragma: no-cache");
    header("Expires: 0");
    
    echo "record1,record2,record3\n";
    die;
    

    etc

    Edit: Here's a snippet of code I use to optionally encode CSV fields:

    function maybeEncodeCSVField($string) {
        if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
            $string = '"' . str_replace('"', '""', $string) . '"';
        }
        return $string;
    }
    

提交回复
热议问题