无法让PHP将CSV下载到用户

问题描述 投票:0回答:1

当我使用此代码将内容下载到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";
}
php
1个回答
-1
投票

除了在header()前面移动fputcsv(),你可以使用output buffering来开始,通过在开头调用ob_start()和在脚本结束时调用ob_end_flush()

© www.soinside.com 2019 - 2024. All rights reserved.