Page 1 of 1

Saving data to CSV.

Posted: Fri Apr 24, 2020 5:13 pm
by mariostg
I have this very basic function that saves records as csv, but when it saves, it also inlcudes the page content, header, etc. There has to be a trick, probably stupid, but I cannot figure it out.

Code: Select all

    public function toXL(){
        $this->GetMatches();
        echo $this->_totalmatchingrows. "Lines found<br>";
        $filename = "registraire_" . date('Ymd_HMS') . ".csv";
        
        $out = fopen("php://output", 'w');
        $this->MoveFirst();
        header("Content-Disposition: attachment; filename=\"$filename\"");
        header("Content-Type: text/csv; charset=UTF-8");
        while(!$this->EOF()){
            $row = $this->fields;
            $retval = fputcsv($out, array_values($row), ',', '"');
            //echo "<br>Wrote ". $retval.'<br>';
            $this->MoveNext();
        }
        fclose($out);
    }

Re: Saving data to CSV.

Posted: Fri Apr 24, 2020 9:35 pm
by SwBd
Hello,

just add

Code: Select all

exit;
at the very end

Re: Saving data to CSV.

Posted: Sat Apr 25, 2020 1:08 pm
by Jo Morg
You'll need to clear the output buffers from any stored output right before sending the headers, and then kill the process right after the output to prevent further content being printed to the buffers.

Code: Select all

    public function toXL(){
        $this->GetMatches();
        echo $this->_totalmatchingrows. "Lines found<br>";
        $filename = "registraire_" . date('Ymd_HMS') . ".csv";
       
        $out = fopen("php://output", 'w');
        $this->MoveFirst();
       /***************************************/
       $handlers = ob_list_handlers();
       for ($cnt = 0; $cnt < sizeof($handlers); $cnt++) { ob_end_clean(); }
       /***************************************/
        header("Content-Disposition: attachment; filename=\"$filename\"");
        header("Content-Type: text/csv; charset=UTF-8");
        while(!$this->EOF()){
            $row = $this->fields;
            $retval = fputcsv($out, array_values($row), ',', '"');
            //echo "<br>Wrote ". $retval.'<br>';
            $this->MoveNext();
        }
        fclose($out);
       die; // exit or die here to prevent further output to the buffer
    }
 

[SOLVED] Re: Saving data to CSV.

Posted: Sun Apr 26, 2020 12:16 am
by mariostg
Jo Morg.
Thanks. That solved the problem.