我正在尝试使用 select 语句通过 php 导出带有空字段的 csv 文件,但空列未包含在 csv 输出中。
$query = "SELECT client_last_name,'','','','', client_first_name FROM billing_line_item";
$result = mysqli_query($connection, $query);
if (!$result) {
die("Query Failed" . mysqli_error($connection));
} else {
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
fputs($output, implode($header1, ',')."\n");
while ($row = mysqli_fetch_assoc($result)) {
fputs($output,implode($row, ',')."\n");
}
fclose($output);
exit();
}
我的 csv 文件中的输出如下:
Print_R of Array:
Array
(
[client_last_name] => LastName
[] =>
[client_first_name] => FirstName
)
Output: LastName,,FirstName
Expecting: LastName,,,,,FirstName
最佳答案
由于您没有为空列分配任何别名,因此它们都使用相同的空字符串命名。但是关联数组不能有重复的键,因此当您使用 mysqli_fetch_assoc 时只能得到一个空列。相反,请使用mysqli_fetch_row
,它返回一个数字索引数组。
或者,您可以为空列分配别名。
$query = "SELECT client_last_name,'' AS empty1, '' AS empty2, '' AS empty3, '' AS empty4, client_first_name FROM billing_line_item";
关于php - 将空列插入 csv - php 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35780370/