我已经阅读了有关stackoverflow
中描述的问题的所有主题,这些主题链接到函数中重复值的问题fputcsv
。不幸的是,我正在使用PDO
和psql
(使用简单的mysql
连接器描述了所提出的解决方案)
但首先我将描述我的问题显示一些代码。这是我放的:
$db=ConnectionFactory::CreateConnection();
$fileName = 'somefile.csv';
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename={$fileName}");
header("Expires: 0");
header("Pragma: public");
$fh = @fopen( 'php://output', 'w' );
$query = "SELECT * FROM person";
$results = $db->query($q)->fetchall();
$headerDisplayed = false;
foreach ( $results as $data ) {
// Add a header row if it hasn't been added yet
if ( !$headerDisplayed ) {
// Use the keys from $data as the titles
fputcsv($fh, array_keys($data));
$headerDisplayed = true;
}
// Put the data into the stream
fputcsv($fh, $data);
}
// Close the file
fclose($fh);
// Make sure nothing else is sent, our file is done
exit;
我得到CSV
文件包含双精度值,例如:
"name","name","phone","phone","email","email"
"John","John","501231","501231","test","test"
"Bob","Bob","1111","1111","test2","test2"
当我尝试执行函数pg_fetch_array
时出现错误:
pg_fetch_array() expect parameter 1 to be resource, array given
我该怎么做才能修复我的 csv?
PDO的默认值是PDO::ATTR_DEFAULT_FETCH_MODE,这是将行作为枚举数组和关联数组检索,因此您将获得重复
提取为枚举或关联,但不要简单地默认它
$db->query($q)->fetchall(PDO::FETCH_ASSOC);