fputcsv创建文件但将其下载为空

时间:2016-03-23 16:25:58

标签: php mysql csv fputcsv

我有这段PHP代码旨在从mySQL数据库中检索数据,并将其导出到CSV文件,该文件必须在创建后自动下载。

$connection = mysqli_connect($host, $username, $password, $dbname) or die("Connection Error " . mysqli_error($connection));

// fetch mysql table rows
$sql = "select * from users";
$result = mysqli_query($connection, $sql) or die("Selection Error " . mysqli_error($connection));

$fp = fopen('users.csv', 'w');

while($row = mysqli_fetch_assoc($result)) {
    fputcsv($fp, $row);
}

fclose($fp);

header('Content-Type: text/csv');

header('Content-Disposition: attachment; filename="users.csv"');

mysqli_close($connection);

问题在于:

  • 检索数据。
  • 在export.php文件的同一目录中检索服务器上的CSV文件及其中的数据
  • 下载名称相同的文件但它是空的

感谢。

1 个答案:

答案 0 :(得分:0)

您将其写入名为users.csv的文件,但您强制用户下载的文件是该页面的输出。

只要您的查询正确,一旦PHP脚本运行,就应该在与包含正确数据的PHP文件相同的目录中有一个名为users.csv的文件。

您需要将数据输出到浏览器,以便将其归因于您正在下载的文件。

试试这个:

//Connect to database
$connection = mysqli_connect($host, $username, $password, $dbname) or die("Connection Error " . mysqli_error($connection));

//Fetch mysql table rows
$sql = "select * from users";
$result = mysqli_query($connection, $sql) or die("Selection Error " . mysqli_error($connection));

//Close connection
mysqli_close($connection);

//Set $output
$output = "";

//Set header values
$headers = array("Header 1", "Header 2", "Header 3");

//Insert header values to $output
foreach($headers as $h){
    $output .= fieldCheck($h) . ",";
}
$output = rtrim($output, ","). "\n";

//Iterate through results
while($row = mysqli_fetch_assoc($result)) {
    foreach($row as $cell){
        //Comma-separate each value
        $output .= fieldCheck($cell).",";
    }
    //Remove last comma of each line and add newline
    $output = rtrim($output, ",") . "\n";
}

//Set headers
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="users.csv"');

//Output
echo $output;

exit;

//Function in case of comma in field
function fieldCheck($string){
    if(strpos($string, ",") !== false){
        $string = '"'.$string.'"';
    }
    return $string;
}