dtc88867 2015-07-28 21:37
浏览 36
已采纳

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.

  • 写回答

2条回答 默认 最新

  • doulin6088 2015-07-28 22:18
    关注

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算