How to make fputcsv “echo” the data

后端 未结 4 1879
孤独总比滥情好
孤独总比滥情好 2021-01-01 09:56

I need a way to make the fputscv function write data to the browser on-the-fly instead of creating a temporary file, saving data into that file and doing a echo file_g

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-01 10:26

    Producing a CSV is actually not all that difficult (parsing a CSV is a little bit more involved).

    Sample code for writing a 2D Array as CSV:

    $array = [
        [1,2,3],
        [4,5,6],
        [7,8,9]
    ];
    
    // If this CSV is a HTTP response you will need to set the right content type
    header("Content-Type: text/csv"); 
    
    // If you need to force download or set a filename (you can also do this with 
    // the download attribute in HTML5 instead)
    header('Content-Disposition: attachment; filename="example.csv"')
    
    // Column heading row, if required.
    echo "Column heading 1,Column heading 2,Column heading 3\n"; 
    
    foreach ($array as $row) {
        $row = array_map(function($cell) {
            // Cells containing a quote, a comma or a new line will need to be 
            // contained in double quotes.
            if (preg_match('/["\n,]/', $cell)) {
                // double quotes within cells need to be escaped.
                return '"' . preg_replace('/"/', '""', $cell) . '"';
            }
    
            return $cell;
        }, $row);
    
        echo implode(',', $row) . "\n";
    }
    

提交回复
热议问题