下面的代码正确地从mysql表中导出数据,但列名不会显示在输出的csv文件中。请帮忙
if(isset($_POST["export"])){
$branchcode=$_POST['branchcode'];
$start=$_POST['start'];
$end=$_POST['end'];
$sql=mysqli_query($conn,"select tk_file,tk_date,userid,tk_from,tk_to from rfc_timekeeping_history where branchcode='$branchcode' and (tk_date between '$start' and '$end');")or die(mysqli_error());
$output = "";
$columns_total = mysqli_num_fields($sql);
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysqli_fetch_fields($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";
while ($row = mysqli_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
$filename = "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
}
答案 0 :(得分:1)
使用标准php方法写入csv文件(fputcsv
)和使用stdout
流的不同方法,您可以尝试这些方法。在重写记录集以实际处理记录集数据之前,在第一个循环中获取列名。
<?php
if( isset( $_POST["export"], $_POST['branchcode'], $_POST['start'], $_POST['end'] ) ){
$filename = "myFile.csv";
$branchcode=$_POST['branchcode'];
$start=$_POST['start'];
$end=$_POST['end'];
/* store columns names in this array */
$headers=array();
/* Run the query */
$sql = mysqli_query( $conn, "select `tk_file`,`tk_date`,`userid`,`tk_from`,`tk_to` from `rfc_timekeeping_history` where `branchcode`='{$branchcode}' and ( `tk_date between` '{$start}' and '{$end}');")or die(mysqli_error());
/* fetch the fields */
$fields = mysqli_fetch_fields( $sql );
/* add each column name to the array */
foreach( $fields as $field ) {
$headers[]=$field->name;
}
/* establish basic csv formatting parameters */
$delimiter=',';
$enclosure='"';
/* write output to stdout */
$output=fopen('php://output','w+');
fputcsv( $output, $headers, $delimiter, $enclosure );
/* rewind the recordset to begin processing data */
mysqli_data_seek( $sql, 0 );
/* process each row - add to stdout */
while( $row = mysqli_fetch_array( $sql ) ) {
fputcsv( $output, $row, $delimiter, $enclosure );
}
/* close stdout stream */
fclose( $output );
/* send the data */
header("Content-Type: application/csv");
header("Content-Disposition: attachment; filename={$filename}");
ob_flush();
exit();
}
?>