How to make fputcsv “echo” the data

后端 未结 4 1876
孤独总比滥情好
孤独总比滥情好 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:22

    Found this on the PHP docs website, first comment under the function reference:

    function outputCSV($data) {
      $outstream = fopen("php://output", 'w');
      function __outputCSV(&$vals, $key, $filehandler) {
        fputcsv($filehandler, $vals, ';', '"');
      }
      array_walk($data, '__outputCSV', $outstream);
      fclose($outstream);
    }
    

    And a second option:

    $csv = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');
    fputcsv($csv, array('blah','blah'));
    rewind($csv);
    
    // put it all in a variable
    $output = stream_get_contents($csv);
    

    Hope this helps!

    BTW the PHP docs should always be your first stop when trying to figure things out. :-)

    0 讨论(0)
  • 2021-01-01 10:22

    By a comment on the PHP site

    <?php
    $out = fopen('php://output', 'w');
    fputcsv($out, array('this','is some', 'csv "stuff", you know.'));
    fclose($out);
    ?>
    
    0 讨论(0)
  • 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";
    }
    
    0 讨论(0)
  • 2021-01-01 10:35

    As the original asker wanted to "write to the browser on the fly", maybe is worth noting (as was my case and noone mentioned it) that if you want to force a file name and a dialog asking to download a file in the browser, you must set the proper headers before outputting anything with fputcsv:

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=myFile.csv');
    
    0 讨论(0)
提交回复
热议问题