Why is fputcsv producing duplicate columns?

不羁岁月 提交于 2021-02-16 19:00:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!