My csv export displaying html, how to get rid of?

主宰稳场 提交于 2019-11-27 22:43:16

问题


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.

Here is my code on the file that is being required.

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');

}

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.


回答1:


Got it working!

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.

Here is my code.

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();
}



回答2:


Place, ob_end_clean(); before you output the csv.

ob_end_clean() meaning: "Clean (erase) the output buffer and turn off output buffering" - PHP manual.




回答3:


The logic for it to work is to construct your php script so that it:

  1. first echoes all the html/javascript... content intended for the browser page like echo "<html...>;" (this already uses php's output buffer behind the scenes)
  2. after that cleans the php's output buffer so far, with ob_end_clean() (depending how ob_start() was called this may prevent the previous export) or ob_clean() which just sends content so far to the browser and cleans the buffer without turning it off.
  3. lastly uses this clean output buffer again to export any further content (as downloadable csv in our case) to the browser, like shown above by wowzuzz. So if any html is echoed by the script after that, it will be included in the csv as well.


来源:https://stackoverflow.com/questions/13316293/my-csv-export-displaying-html-how-to-get-rid-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!