fpassthru表现得很奇怪(发送页面html而不是我想要的文件)

I'm really really new to PHP, so if you can explain it to me what my code is actually doing and why the result is what it is I would appreciate very much. I'm probably screwing up something very simple.

Basically I want to query a MySQL database, create a csv with the data, and download the csv. Pretty simple. Here is my code:

<?php
    include("Includes/PHPheader.php");
    $query_string = $_SERVER['QUERY_STRING'];
    parse_str($query_string);

    $sql = "SELECT many_columns_i_removed_from_this_sample_code FROM table WHERE id = '".$id."'";
    $result = $conn->query($sql);
    $row = $result->fetch_assoc();    

    $f = fopen("csv/tmp.csv", "w");
    fputcsv($f, array_keys($row),';');
    fputcsv($f,$row,';');
    rewind($f);
    header('Content-Type: application/csv');
    header('Content-Disposition: attachment; filename="tmp.csv"');
    fpassthru($f);
    fclose($f);
?>

There are some HTML code below it that shouldn't affect anything, but just in case here it is.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
    </body>
</html>

Well, I thought this would download my csv with no problem. If I go to the csv folder, there it is, the tmp.csv file I created, with the proper header and data.

But when I open the tmp.csv file I downloaded, it is actually the html code of the page, and not the data I expected.

What is going on?

In case it helps, I'm using WebMatrix 3.0.

There are two things going on, probably. First, You are trying to read (fpassthru) from a file opened for writing (fopen(..., "w")), so You are not able to read anything from the file. Then, after that "reading nothing" goes Your HTML code, which naturally appends to Your output. Try this:

$f = fopen("csv/tmp.csv", "w+");
...
fclose($f);
exit;

Could you please try?

header("Content-type: application/vnd.ms-excel");

instead of

header('Content-Type: application/csv');

I have a test code of CSV output, have a look - https://foowms.googlecode.com/svn/trunk/stockincsv.php

A very informative thread of Stack Overflow Setting mime type for excel document

==============================================

If csv file open, write and save, then you should do as follows-

$list = array ("Peter,Griffin,Oslo,Norway");
$file = fopen("csv/tmp.csv","w");

foreach ($list as $line) {
fputcsv($file,explode(',',$line));
}

fclose($file);

==============================================

You also could try this

fputcsv($fp, array_values($list), ';', ' ');

instead of

fputcsv($f, array_keys($row),';');