-2

So I have this piece of code here that reads the data from the database and then it should prompt me the "Open/Save as" window but it doesn't. Any idea where the problem might be? It echo-es the results but the download window doesn't appear.

    <?php/*
mb_http_output('UTF-8');
mb_http_input('UTF-8');
mb_language('uni');
mb_regex_encoding('UTF-8');
ob_start('mb_output_handler');
header('Content-type: text/html; charset=utf-8');*/
?>
<?php


$conn = mysql_connect('localhost', 'xxxx', 'xxxx') or die(mysql_error());
mysql_select_db('nooruse', $conn) or die(mysql_error($conn));

$query = sprintf('SELECT osakond as Osakond, soetusaasta, it_number, tooteruhm, mudeli_nimetus, sn, riigivara_nr, inventaari_nr, maja, ruum, vastutaja, markus FROM norse5_proov');
$result = mysql_query($query, $conn) or die(mysql_error($conn));

header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=export.csv');

$row = mysql_fetch_assoc($result);
if ($row) {
    echocsv(array_keys($row));
}

while ($row) {
    echocsv($row);
    $row = mysql_fetch_assoc($result);
}

function echocsv($fields)
{   
    echo $query ,"<br>";
    $separator = '';
    foreach ($fields as $field) {
        if (preg_match('/\\r|\\n|,|"/', $field)) {
            $field = '"' . str_replace('"', '""', $field) . '"';
        }
        echo $separator . $field;
        $separator = ',';
    }
    echo "\r\n";
}
?>

Thanks in advance!

Erlend Anderson
  • 53
  • 1
  • 10

4 Answers4

1

You're not allowed to have any output before you send the headers via header(). That includes whitespace before the first <?php and a newline between ?> and <?php.

johankj
  • 1,765
  • 16
  • 34
1

I am using the headers like below. Try it

header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header('Content-disposition: filename='.$filename.'.csv');
print $csv_output;
Samy
  • 632
  • 4
  • 14
0

Use this header,

header('Content-type: application/force-download');

it will work.

Ravichandran Jothi
  • 3,028
  • 11
  • 52
  • 82
0

try using these headers:

header("Content-Description: Download File");
header("Content-Disposition: attachment; filename=whatever.csv");
header("Content-Type: text/plain");
header("Content-Length: ".strlen($output));

where $output

is a capture variable of your echoed output.

djjjuk
  • 368
  • 1
  • 2
  • 14