Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSV Downloaded To Chrome - Error: MIME Type text/csv

I am using jQuery to recognise a click on a button which then fires a call to a file:

window.location.href = "url";

This file queries the database, returns results then writes it to a CSV file. I have the following headers set:

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

This works on all browsers except Chrome which returns the following error in the console log "Resource interpreted as Document but transferred with MIME type text/csv: "url"".

The weird thing is that if I call the file directly it works in all browsers.

Code:

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

                header('Content-Type: text/csv;');
                header('Content-Disposition: attachment; filename=data.csv');
                header("Expires: 0");
                header("Cache-control: private");

                //Field Headers
                $ncols = oci_num_fields($stid);
                $headers_row = array();
                for ($i = 1; $i <= $ncols; ++$i) {

                    $headers_row[] = oci_field_name($stid, $i); 

                }

                while ($row = oci_fetch_array($stid, OCI_NUM+OCI_RETURN_NULLS)) {

                    if(!empty($row)){
                        if(!empty($headers_row)){
                            fputcsv($fp, $headers_row);
                            $headers_row = '';
                        }

                        fputcsv($fp, $row);
                    }

                }

                fclose($fp);                    
                oci_close($conn);

Anyone got any ideas?

like image 764
Elliot Avatar asked Feb 01 '13 13:02

Elliot


1 Answers

try {
    $conn = new PDO("mysql:host=$servername;dbname=db_1", $username, $password);
    //set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //echo "Connected successfully"; 
    }
catch(PDOException $e)
    {
      echo "Connection failed: " . $e->getMessage();
    }


$query = $conn->prepare("SELECT * FROM csv_filds order by id asc");
$query->execute();
$data = "";
 while($row=$query->fetch(PDO::FETCH_BOTH)){ 
  $data .= $row['id'].",".$row['Name'].",".$row['father_name'].",".$row['address']."\n";
}
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="csvfile.csv"');
echo $data; exit();
like image 163
Developer Dev Avatar answered Sep 22 '22 16:09

Developer Dev