Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...