将空列插入csv - php的问题

时间:2016-03-03 18:43:19

标签: php mysql csv

我正在尝试使用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

1 个答案:

答案 0 :(得分:1)

由于您没有为空列分配任何别名,因此它们都使用相同的空字符串命名。但是关联数组不能包含重复键,因此在使用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";