问题
I am adding a download button to a WordPress site that will query our database, and offer up the result as a CSV.
Everything works, except the CSV produced has a duplicate column for each column it returns.
We have checked the SQL query and it does not have duplicates.
Here's how we are generating the CSV:
$rows = //Call to SQL query function
$fp = fopen('php://output', 'w');
fputcsv($fp, array_keys($rows));
foreach ($rows as $row) {
fputcsv($fp, $row);
}
$filename = "EventResults.csv";
header('Content-Type: text/csv');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=$filename");
We turn the SQL return into a PHP array like this:
$sql = "SELECT * FROM TABLE";
$statement = $this->db->prepare($sql);
$statement->execute();
return $statement->fetchAll();
The results look like this:
Lance,Lance,Armstrong,Armstrong,DEX,DEX,70,70,1,1,60,60,SEC,SEC,"10; 20; 30; 40","10; 20; 30; 40"
When they should look like this:
Lance,Armstrong,DEX,70,1,60,SEC,"10; 20; 30; 40"
What is causing the duplicates, and how can we get rid of them?
回答1:
The PDO method fetchAll()
has a parameter fetch_style
which as documented will return an array with both numerical and named associative keys causing you to have duplicates when you iterate over the array.
You can set it using one of the PDO Fetch constants documented here - they all start with PDO::FETCH_
and use that to get either an associative array (PDO::FETCH_ASSOC
) or a numerical array (PDO::FETCH_NUM
)
return $statement->fetchAll(PDO::FETCH_ASSOC);
回答2:
This works in MSSQL to prevent duplicate columns:
while ( $row = mssql_fetch_array($results, MSSQL_ASSOC) ) {
fputcsv($fp, $row);
}
来源:https://stackoverflow.com/questions/23485721/why-is-fputcsv-producing-duplicate-columns