How to make fputcsv “echo” the data

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

提交回复
热议问题