PHP导出为空内容

时间:2015-04-07 09:22:32

标签: php export-to-csv

我在这里遇到问题。我想从mysql数据库中检索所有数据并将其导出。但是,导出的csv文件不包含任何内容。请帮帮我。

if(isset($_POST['export'])){
$filename = 'applicants '.date('m-d-Y').'.csv'; 
$tableName="applicants";
$sql=mysql_query("select * from applicants");
$num_rows=mysql_num_rows($sql);
mysql_data_seek($sql, 0);
$row = mysql_fetch_assoc($sql);
$fp = fopen($filename,"w");
$seperator="";
$comma="";
$tableName="applicants";

foreach($row as $name => $value)
{
    if($name==""){
        $name=" ";
    }
    $seperator .= $comma . '' .str_replace('','""','"'.$name.'"');
    $comma = ",";

}
$seperator .="\n";
fputs($fp,$seperator);
mysql_data_seek($sql, 0);
while($row = mysql_fetch_assoc($sql)){
    $seperator="";
    $comma="";
    foreach($row as $name => $value)
    {
        $seperator .= $comma . '' .str_replace('','""','"'.$value.'"');
        $comma = ",";   
    }
    $seperator .="\n";
    fputs($fp,$seperator);
}
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
fclose($fp);
}

2 个答案:

答案 0 :(得分:0)

这是执行此操作的简单方法...根据您进行更改

   // output headers so that the file is downloaded rather than displayed
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=data.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('mysqlColumnName1', 'mysqlColumnName2', 'mysqlColumnName3'));

// fetch the data
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');

// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) 
            fputcsv($output, $row);

答案 1 :(得分:0)

仅发送Content-Disposition标头不会自动附加文件。你应该手动包括它,例如

// ...
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
fclose($fp);
echo file_get_contents($filename);

或者,您可以使用fopen('php://output', 'w');作为Harsh的回答建议。

另外,确实使用fputcsv