0

so, first let me state, before you start providing other suggestions on how to simply export a complete table to a CSV file, that is not what I want to do (my demo code right now suggests that, but I am merely testing the whole downloading through browser shabaz).

I actually want to construct my content to be exported from several tables. never the less, I am merely trying to get the exporting and downloading through the browser working right now.

I got this code from an example online and currently what is happening is it is simply printing out the data to my browser.

here is my code I am testing:

$result = mysql_query("SELECT * FROM results_tb") or die(mysql_error());

    // I hard-code the column names so I can capitalize, add spaces, etc.
    $fields = '"User ID","Test_id","score %","Time taken"'."\n";

    // Iterate through the rows of data
    while ($row = mysql_fetch_assoc($result))
    {
        //echo $row['user_id'];
        $fields .= '"'.$row['user_id'].'","'.$row['test_id'].'","'.$row['score'].'","'.$row['time_elapsed'].'"'."\n";
    }

    // Set our headers
    header('Content-type: text/csv');
    // To display data in-browser, change the header below to:
    // header("Content-Disposition: inline");
    header("Content-Disposition: attachment; filename=event_registrations.csv");

    // Output our data
    echo $fields;

I am assuming this example is pants, so could somebody explain to me how to do this?

many thanks :D

my header response caught with firebug-Lite:

Date    Wed, 18 May 2011 14:15:18 GMT
X-Powered-By    PHP/5.1.6
Content-disposition attachment;filename=MyVerySpecial.csv
Connection  close
Content-Length  992
Server  Apache/2.2.3 (Red Hat)
Content-Type    text/csv
4

1 回答 1

0

我的猜测是您已display_errors设置为关闭,并且在进行这些header()调用之前您正在输出一些东西。这将导致您看到的行为。

首先,编辑您的php.ini文件并确保它display_errors已打开并且您的 PHP 脚本中有错误报告(例如error_reporting(E_ALL);)。现在您的屏幕上可能会出现错误。类似于以下内容:

Cannot send header information. Output already started by XXX.php (line YYY).

可能发生的情况是您在发送header()命令之前不小心发送了空格或换行符,并且您正在抑制错误。当您在这些header()调用之前向浏览器发送某些内容时,它们将被忽略。因此,浏览器只会显示您发送的任何内容,而不是让用户下载它。

如果您使用的是 Firefox,您还可以使用 Firebug 扩展来检查下载的 HTTP 响应标头。

于 2011-05-18T13:56:56.173 回答