Search code examples
phpcsvpdoexport-to-excel

exporting a .csv file from download button


EDIT: I changed "echo($row)" to "print_r($row)" and now the csv that's being downloaded has each array in parenthesis with all the data mentioned, but how do I customize the way it all can be printed?

Right now, it's printing:

Array ( [id]=>1 [firstname]=>"Timmy" ) Array ( ....

(where each line is the next row in the excel spreadsheet)

How would I make this output so that each record has it's own row? for example the first column in excel would be id, then the second would be firstname, with each record it's own row?

I've got a link in my main.php:

<a class="btn" href="export.php">Export</a>

Then here's my export.php file:

<?php

//open database connection
try {
    $db = new PDO('mysql:host=localhost;dbname=DBNAME;charset=utf8',
                    'DBUSER',
                    'DBPASS');

    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $ex) {
    echo "did not connect...";
}

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

$sql = "SELECT * FROM table_name;";

$sth = $db->prepare($sql);
$sth->execute();

$filename = date('d.m.Y').'.csv';

$data = fopen($filename, 'w');

while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
    fputcsv($data, $row);
    print_r($row);
}

echo "\r\n";

fclose($data);

?>

Solution

  • In order to get an associative array to be placed properly into your file you'll need to parse the array and then put the line in the file:

    while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
        $csv = implode(',', $row) . "\n";
        fwrite($data, $csv);
        print_r($csv);
    }