doufen2769 2014-05-20 14:13
浏览 87
已采纳

将PHP变量的内容下载到文件中

I have this data that I get from my MySQL table and I've stored it in a variable called $arr. I've json_encoded it into a $json variable:

$arr = array();
    while ($blah = mysqli_fetch_assoc(...)) {
          $arr[key] = value;
    }
$json = json_encode($arr);

The thing that I'm trying to do is to download the contents of just the $json variable into a .json file without saving it on the server. But when I try to do that using

        header('Content-Type: text/plain');
        header('Content-Disposition: attachment; filename='.$file.'');
        header('Content-Transfer-Encoding: binary');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        echo $json;

(where $file is a generated name for the downloaded file) I get something like this:

<!DOCTYPE html>
<html>
    <head>
          ....
    </head>
    <body>

<a ...>...</a>{"field":"value","field2":"ИзвеÑтиÑ","field3":"ÐОВ", ...} </body></html>

or the whole .php file content in other words... And as you can see, the encoding is all messed up.

Can you help me identify the problem and possibly give me any ideas on how to fix it.

Any help would be really appreciated : ]

  • 写回答

2条回答 默认 最新

  • doupao1530 2014-05-20 14:19
    关注

    This is most likely because you are outputting your HTML before the echo $json line. There should be nothing printing to the page before a header() function. I usually have a separate PHP file (away from the template of a page) to build downloadable files.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

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