我正试图将MySQLi查询写入可下载的CSV。以下标题打开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。有人能告诉我为什么会这样吗?
这是我第一次尝试使用比hello世界更复杂的PHP脚本。如果答案非常简单或明显,请道歉。
清理代码一次,以循环返回的行,并使用mysqli_error函数:-
<?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);
}
}
}
像这样尝试
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标头放置在"if"循环
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程序节省大量内存,运行速度也会更快(如果您有一个大数据集,这将非常值得注意)。