CSV data printing to screen from PHP instead of going to file

I have some PHP code that grabs data from a MySQL db and outputs to CSV. It was working fine but for no apparent reason it’s now printing to the browser screen and not creating a new file with the data. The data being outputted is all fine but I need it to go into a new CSV file.

This is the code (which was working and hasn’t been edited)

if($_POST['exportapproved'])
{
    //echo 'Export';
    //$result = $_POST['getagencies'];
    $result = $mysqli->query('SELECT * FROM certificates WHERE IsApproved LIKE "Y" AND IsVoided NOT LIKE "Y" AND IsArchived NOT LIKE "Y" ORDER BY CertificateID DESC'); 
if (!$result) { die('Couldn\'t fetch records'); }
$headers = $result->fetch_fields();
foreach($headers as $header) {
    $head[] = $header->name;
}
$fp = fopen('php://output', 'w');
ob_end_clean();
if ($fp && $result) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="export-approved.csv"');
    header('Pragma: no-cache');
    header('Expires: 0');
    fputcsv($fp, array_values($head)); 
    while ($row = $result->fetch_array(MYSQLI_NUM)) {
        fputcsv($fp, array_values($row));
    }
    die;
}
}

I read some posts on other forums which suggested changing to the content type, so I have also tried header(“Content-Type: application/ms-excel”) and header(“Content-type: application/octet-stream”); but to no avail.

Any ideas? Thanks!

I’ve never tried

$fp = fopen('php://output', 'w');

so I’m not sure what it does but I always use a file name eg

$fp = fopen('export.csv', 'w');

Thanks, well I tried that but absolutely nothing happens- no error, no few CSV file created- nothing.

I don’t think you want any of the headers. A CSV file is s straightforward text file.

I’ve not seen any examples that don’t use headers- do you have one that works? Also, I would have thought fopen wouldn’t work on a file held locally on the user’s local filesystem (e.g PC)??

The only script I can lay my hands on right now is appending a single record; nothing as sophisticated as your requirement, and it simply uses fwrite(). The CSV file started off as a blank file.

$fh = fopen($dir.'readings.csv', 'a');
fwrite($fh, $stats);
fclose($fh);

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.