PHP:将 MYSQL 查询写入 CSV

PHP: Writing a MYSQL query to CSV

我正在尝试将 MySQLi 查询写入可下载的 CSV。以下 headers 打开 CSV 流:

$fileName = ''; //empty file name, file name is cast later
header("Cache=Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename={$fileName}");
header("Expires: 0");
header("Pragma: public");
$fh = @fopen( 'php://output', 'w' );

在此之下,我尝试查询并将查询的每一行转换为 CSV 文件中的新行:

if(isset($_POST["Submit"]) && ($_POST['Weight'] == 'Weight')){
    $fileName .= 'OutputWeightNull.csv';
    $query = mysqli_query($conn, 'SELECT * FROM  `Some_Table` WHERE WEIGHT = 0 OR weight IS NULL')or die(mysql_error());
    $result = mysqli_fetch_array($query) or die(mysql_error());
    $headerDisplayed = false;
    foreach ($result as $data){
    if (!headerDisplayed){
    fputcsv($fh, array_keys());
    $headerDisplayed = true;
        }
        fputcsv($fh, $data);
    }
}

CSV 正在按需要下载到浏览器,但它显示为空,查询结果未发送到 CSV。谁能指出我正确的方向,说明为什么会这样。

这是我第一次尝试 PHP 比 hello world 更复杂的脚本。如果答案非常简单或显而易见,我们深表歉意。

这样试试

if(isset($_POST["Submit"]) && ($_POST['Weight'] == 'Weight')){
 $fileName = 'OutputWeightNull.csv';
 $fh = @fopen( 'php://output', 'w' );
 header("Cache=Control: must-revalidate, post-check=0, pre-check=0");
 header('Content-Description: File Transfer');
 header("Content-type: text/csv");
 header("Content-Disposition: attachment; filename={$fileName}");
 header("Expires: 0");
 header("Pragma: public");

 $query = mysqli_query($conn, 'SELECT * FROM  `Some_Table` WHERE WEIGHT = 0 OR weight IS NULL')or die(mysql_error());
 $headerDisplayed = false;
 while($result = mysqli_fetch_array($query, MYSQLI_ASSOC)) {  
  if (!$headerDisplayed){
   fputcsv($fh, array_keys($result));
   $headerDisplayed = true;
  }
  fputcsv($fh, $result);
 }
}

您需要将 csv header 放在 'if' 循环中

清理代码以围绕返回的行循环,并使用 mysqli_ 错误函数:-

<?php 

if(isset($_POST["Submit"]) && ($_POST['Weight'] == 'Weight'))
{
    $fileName = ''; //empty file name, file name is cast later
    header("Cache=Control: must-revalidate, post-check=0, pre-check=0");
    header('Content-Description: File Transfer');
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename={$fileName}");
    header("Expires: 0");
    header("Pragma: public");
    $fh = @fopen( 'php://output', 'w' );

    $fileName .= 'OutputWeightNull.csv';
    $query = mysqli_query($conn, 'SELECT * FROM  `Some_Table` WHERE WEIGHT = 0 OR weight IS NULL') or die(mysqli_error($conn));
    if ($result = mysqli_fetch_array($query, MYSQLI_ASSOC))
    {
        fputcsv($fh, array_keys($result));
        fputcsv($fh, $result);
        while ($result = mysqli_fetch_array($query, MYSQLI_ASSOC))
        {
            fputcsv($fh, $result);
        }
    }
}

MySQL 具有用于将数据直接输出为 CSV 格式的内置查询类型。

修改您的 SELECT 查询,使其采用以下格式:

SELECT fieldlist FROM table
INTO OUTFILE 'filename.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';

现在您不必执行任何循环或类似的操作; PHP 所要做的就是 运行 该查询,然后对 MySQL 生成的 CSV 文件执行 readfile(),最后将其从磁盘中删除。

这将为您的 PHP 程序节省大量内存,并且 运行 速度也会快很多(如果您的数据集很大,这将非常明显)。