[PHP] using PHP to generate and download the CSV file


The principle is simple , That is to output a header with PHP , The browser can download the file directly

The cell contents are separated by English commas , In order to prevent garbled code , A transcoding operation is performed on the Chinese character part , From utf8 to GBK

In order to make the cell look more intuitive, you will increase the number of cells so that it will not appear when you look at them#########

For example, the following one downloads the moveusers array as a CSV file

if(isset($_REQUEST['act'])&& $_REQUEST['act']=="downloadAll") {
    $outformat = "entmove.csv";
    $title = "email name, name, email password, move status, start time, end time, total number of emails, number of received emails, number of failed emails;";
    $data = "";
    foreach ($moveUsers as $b) {
        $status = iconv("utf-8", "gbk//IGNORE", $b['status_text']);
        $realName = iconv("utf-8", "gbk//IGNORE", $b['realName']);
        $data .= "{$b['account']}\t,{$realName}\t,{$b['password']},{$status}\t,{$b['movetime']}\t"
            . ",{$b['endtime']}\t,{$b['totle']},{$b['successnum']},{$b['failnum']}\n";
    $title = iconv("utf-8", "gbk//IGNORE", $title);
    $data = $title . $data;
    header("Cache-control: private");
    header("Pragma: public");
    header('Content-type: application/x-csv');
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 5')) {
        header("Content-Disposition: inline; filename=$outformat");
    } else {
        header("Content-Disposition: attachment; filename=$outformat");
    echo $data;





Recommended Today

Large scale distributed storage system: Principle Analysis and architecture practice.pdf

Focus on “Java back end technology stack” Reply to “interview” for full interview information Distributed storage system, which stores data in multiple independent devices. Traditional network storage system uses centralized storage server to store all data. Storage server becomes the bottleneck of system performance and the focus of reliability and security, which can not meet […]