Getting a query in csv format and then forcing an Excel download issue

Ask a question
1

I am attempting to get the results from my query in a delimited format that when the “Download File” submit button is pressed forces a csv Excel sheet to download with my query results in it.

I am unsure what I am doing wrong. I am getting the following errors:

Warning: explode() expects parameter 2 to be string, array given in /home4/public_html/csvTest.php on line 25

Warning: fputcsv() expects parameter 2 to be array, null given in /home4/public_html/csvTest.php on line 25

Warning: Cannot modify header information - headers already sent by (output started at /home4/public_html/csvTest.php:25) in /home4/public_html/csvTest.php on line 28

Warning: Cannot modify header information - headers already sent by (output started at /home4/public_html/csvTest.php:25) in /home4/public_html/csvTest.php on line 29

And this error in the console after the submit button is clicked:

Refused to display 'https://csvTest?' in a frame because it set 'X-Frame-Options' to 'deny'.

Can anyone help me in what I am doing wrong with this?

Full code:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$file_name = "subscriber_list.csv";
$file = fopen("subscriber_list.csv","w");

try {
    $servername = 'localhost';
    $usernameCon = '';
    $passwordCon = '';
    $con = new PDO('mysql:host='.$servername.';dbname=name', $usernameCon, $passwordCon);

    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql_subscribers = "
        SELECT *
        FROM test_notif
        ORDER BY date_subscribed
    ";
    $subscriber_stmt = $con->prepare($sql_subscribers);
    $subscriber_stmt->execute();
    $subscriber_rows = $subscriber_stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($subscriber_rows as $subscriber_row) {
        fputcsv($file,explode(',',$subscriber_row));
    }

    header("Content-Type: application/pdf");
    header("Content-Disposition: attachment; filename='.$file_name.'");

    fclose($file);
}   
catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
Coin iconoffer bounty
add comment

0 Answer

Your Answer