我的csv导出显示html,如何摆脱? [英] My csv export displaying html, how to get rid of?

查看:348
本文介绍了我的csv导出显示html,如何摆脱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经看过这个问题,我在尝试了一些解决方案后,无法让这个工作正常。问题是我不能得到我的数据导出为正确的CSV格式。在我添加我的ob_end_clean之前,它会导出一个csv与html,现在它不给我一个csv,只是文本。

I've seen this asked before and I am having trouble getting this to work properly after trying a number of solutions. The problem is I can't get my data to export into a csv format properly. Before I added my ob_end_clean it would export out to a csv with html, now it doesn't give me a csv, just text.

这是我的代码在文件

if (isset($_POST["hidden"])) {

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

    $fp = fopen('php://output','w');

    foreach ($list as $row) {
        ob_end_clean();
        fputcsv($fp, $row);
    }

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=data.csv');

}

现在当我进行导出时,回到屏幕上类似于var_dump()。

Right now when I do my export, the data gets put back on the screen similar to a var_dump(). I just simply want this to go to a csv file without having html all over it.

推荐答案

让它工作!

我在页面上的任何内容之前调用了我的csv代码。 :)然后我做了我的连接到我的表,然后我的逻辑为我的代码。我没有ob_start或ob_flush在我的主要文件,这是一个很大的区别。我在while循环之前有ob_clean,然后我在声明标题后做了一个exit()。希望这解释得很好。

I invoked my csv code before anything on the page. :) Then I did my connection to my table, then did my logic for my code. I didn't have an ob_start or ob_flush on my main file which made a big difference. I had the ob_clean before the while loop and then I did an exit() after declaring the header. Hopefully, this explains it well.

这是我的代码。

if (isset($_POST["hidden"])) {
    $sql = "SELECT * FROM `newsletter`";
    $result = mysql_query($sql);

    ob_end_clean();

    $fp = fopen('php://output','w');

    while ($list = mysql_fetch_assoc($result)) {
        fputcsv($fp, $list);
    }

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=data.csv');

    exit();
}

这篇关于我的csv导出显示html,如何摆脱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆