3

I have problem with writing csv file using fputcsv. Its putting the page html also into the csv file. Whats wrong with my code ?

//Excel header
header("Content-Disposition: attachment; filename=\"Delivery_Reports.csv\";" );
header("Content-type: application/vnd.ms-excel");
$out = fopen("php://output", 'w');
$flag = false;
// $result = mysql_query("SELECT * FROM senderids ") or die('Query failed!');
//$sel="SELECT number as MobileNumber ,snum as Sender , msg as Subject ,crdate as Date ,status FROM savemsg WHERE userID='".$_SESSION['id']."' ".$str." ORDER BY sn DESC ";
$result = mysql_query("SELECT `count`, `dnd`, `credit`, `sender_id`, `to`, `message`, `status` FROM `reports` WHERE `unq_id` = '$dlr_id'");
while(false !== ($row = mysql_fetch_assoc($result))){
    if(!$flag){
        $list = array(
            "Total"=>"Total",
            "DND"=>"DND",
            "Credits"=>"Credits",
            "From"=>"From",
            "To"=>"To",
            "Message"=>"Message",
            "Status"=>"Status"
        );
        // display field/column names as first row
        fputcsv($out, array_keys($list), ',', '"');
        $flag = true;
    }
    // array_walk($row, 'cleanData');
    fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • 2
    ... what page html? I can't see any. Maybe add a little more context to your question? – andrewsi Aug 16 '12 at 20:43
  • So, what is this HTML you are seeing? – gen_Eric Aug 16 '12 at 20:43
  • 1
    Presumably this is not the entire content of your php page? What else is there? Any HTML preceeding this code is going to be already in the page output buffer before you create your CSV content... Although you're using `php://output` it's more or less equivalent to using `print` in this case... – Tim Williams Aug 16 '12 at 20:52

4 Answers4

7

You can't guarantee, from within a snippet of code, that nothing else will be output. If the code before this snippet is using output buffering, you can discard the HTML using ob_end_clean. If the code after this snippet is causing the problem, you can simply call die to keep it from running at all. However, if the code before this snippet is outputting HTML directly to the browser, or the code after it outputs HTML and absolutely has to run, then you'll have to modify that code in order to solve your problem.

As Tim mentioned, print, echo and outputting to the pseudo-file php://output do exactly the same thing.

Brilliand
  • 13,404
  • 6
  • 46
  • 58
0

You can also use the keyword continue just before you close the file (fclose($f);). This also works lovely.

heinkasner
  • 425
  • 5
  • 18
0

You can also use exit; after fclose($out); which stopped the output from scraping my html.

Hmerman6006
  • 1,622
  • 1
  • 20
  • 45
  • This is identical to using `die`. – Brilliand Nov 26 '19 at 19:48
  • @Brilliand Yea they are the same, with small differences, ```die``` closes the connection and ```exit``` does'nt; spelling; origins; and exit values. https://stackoverflow.com/questions/1795025/what-are-the-differences-in-die-and-exit-in-php But no other answer here referred to ```exit```. So if somebody new comes along they can see, 'Aaa!, There is an exit option also'. Giving the forum viewer a choice. – Hmerman6006 Nov 27 '19 at 09:18
0

I know it's an old question but it gets found in Google so adding this.

If the HTML is being output by the CMS such as WordPress etc. before you try to create the file, it might help to add ob_clean(); and ob_start(); before you output the header.

For example:

function create_csv($records, $columns){
    ob_clean();
    ob_start();
    header('Content-Type: application/csv');
    header('Content-Disposition: attachment; filename="Export.csv"');
    $fp = fopen('php://output', 'w+');
    // Generate the file content.
    fclose($fp);
    die();
}
Andrew Real
  • 79
  • 1
  • 5