PHP:将MYSQL查询写入CSV [英] PHP: Writing a MYSQL query to CSV

查看:215
本文介绍了PHP:将MYSQL查询写入CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将MySQLi查询写入可下载的CSV。以下标头为CSV打开一个流:

I'm attempting to write a MySQLi query to a downloadable CSV. The following headers open a stream for the 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' );

下面我将尝试查询和转换查询的每一行到一个新行

Below this I have the following which attempts to query and cast each row of the query to a new line in a CSV file:

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。任何人都可以指出我正确的方向,为什么这可能是。

The CSV is downloading to the browser as desired, however it's appearing empty, the query results are not being sent to the CSV. Could anyone point me in the right direction as to why this might be.

这是我第一次尝试PHP脚本,更复杂的hello世界。

This is my my first attempt at a PHP script more complex that the hello world. Apologies if the answers are very simple or obvious.

推荐答案

尝试这样

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);
 }
}

循环

这篇关于PHP:将MYSQL查询写入CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆