php - 使用 PHP 将 MySQL 数据导出到 CSV 文件

标签 php mysql

我在将 MySQL 数据导出到 CSV 文件时遇到一个小问题,它从表中正确打印出数据,但在 csv 文件末尾它还打印了 html 页面代码!

下面是我的代码

$file="billing";
     $i=0;
     $values = mysql_query("SELECT * FROM billing");
     $rown=0;
     while( $row = mysql_fetch_assoc($values)){
     if($rown++==0)
       $csv_output.=implode(";",array_keys($row))."\n";
       $csv_output.=implode(";",array_values($row))."\n";
}

$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: text/csv");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
}

输出:

billing_id;customer_id;user_id;trans_id;transfer;balance;created;text;credit;sender_id      
257;29;;-1;0;500000;1330930434;Payment;500000;      
258;29;;-1;200000;300000;1330930465;Sender ID reg.;0;jkjjhh     
284;32;;-1;0;1000000;1331708884;Payment;1000000;        
285;32;564;268;-120;999880;1331709106;SMS send;;        
286;32;;-1;0;1000000;1331709234;Payment;120;        
287;32;564;269;0;1000000;1331723634;SMS send;;


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">       
    <html xmlns="http://www.w3.org/1999/xhtml">     
    <head>      
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />       
    <title>Client Manger</title>        
    <link rel="stylesheet" href="/style/my-style.css">      
    <form action='./' method='post'>        
    <input type="hidden" name="action" value="billing" class="text">        
    <input type="hidden" name="customer_id" value=""  />

可能是什么原因?

谢谢大家。

最佳答案

您需要在 print $csv_output; 之后使用 exit;die(); 否则页面的其余部分(在关闭的 } (我怀疑是 if 语句的结尾))将打印(因此包含在 CSV 中)。

<小时/>

只是一个想法:最好有两个 PHP 文件来处理这个问题:一个输出 CSV,另一个输出表单。不仅可以让您避免使用 die/exit 或很长的 else 语句,还可以使代码整体更简洁。

<小时/>

另一种想法是,每当您希望第一次(并且仅是第一次)发生某些事情时,最好使用 do...while 。所以这可能是一个更好的选择:

$row = mysql_fetch_assoc($values);
$csv_output.=implode(";",array_keys($row))."\n";
do
{
    // notice how there is no flag needed!
    // also, you don't need to call 'array_values' when imploding
    $csv_output.=implode(";",$row)."\n";
}while( $row = mysql_fetch_assoc($values));

关于php - 使用 PHP 将 MySQL 数据导出到 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10297493/

相关文章:

php - 将Dockerfile从php:7.2-fpm更新到php:7.3-fpm时出错

mysql - 如何删除邻接列表模型中的父级及其子级?

mysql - 选择所有日期时间的数据

PHP 不连续更新记录

php - DOMXPath 和 DOMDocument 对象的调试

javascript - Ajax php 登录表单不指向另一个页面

php - Magento:未发货的项目集合

php - mysql 中 SUM(IF) 条件出现问题

mysql - SQL Case 不标记 null 时

PHP - 调试要求