无法让PHP将CSV下载到用户

时间:2017-11-04 14:13:26

标签: php

当我使用此代码将内容下载到CSV文件和用户时,它只会向网站​​显示查询...

$result = $conn->query($sql);

if (mysqli_num_rows($result) > 0) {
$counter=1;

// open file and put herder to csv file
$file = fopen('php://output', 'w');
fputcsv($file, array('id','name','test1','test2'));
// put content to csv file
while ($row = mysqli_fetch_assoc($result)) {

    fputcsv($file, array($counter++,$row['name'],
                         ($row['test1']!=-1)?$row['test1']:'null',($row['test2']!=-1)?$row['test2']:'null'));
}
$csv_name=(isset($_GET['device'])&&$_GET['device']!='')?$_GET['device']:"all_devices";
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment;'.
       'filename='.$csv_name.'_'.date('Y-m-d').'.csv');
} else {
  echo "No device found";
}

1 个答案:

答案 0 :(得分:-1)

除了在header()前面移动fputcsv()之外,您可以使用output buffering来解决问题,在开始时调用ob_start()并在ob_end_flush()处调用df.reset_index().pivot('HID','gen','views') 你脚本的结尾。