0

I have SQL query that exports data to a CSV. All works well until I go below a certain amount of data in the export.

When I go below this threshold, the records are exported followed by the html of the page.

If I add more characters on the header.html the problem is resolved. Ive tested and retested this, and one character of text anywhere on the html page is the difference between exporting the entire html or just the records.

It sounds too weird to be true, I am hoping someone has experienced something similar and can tell me where to look or what specific part of my code I should be pasting here:

Here is the fputcsv part:

if(isset($_SESSION['query_file']))
{
$query = $_SESSION['query_file'];
unset($_SESSION['query_file']);

$stmt = $dbh->query($query);

$results = $stmt->fetchAll();

$link = 'csv/'. Utils::rand_code(10).'.csv' ;

$fp = fopen(SITE_ROOT.$link,'w');
$first_row = array(
    'Name',
    'ID',
    'Email',
    'Response',
    'Phone'
);

fputcsv($fp, $first_row);

foreach($results as $key=>$value)
{


    $array_add = array(
        $value['user_last_name'].''.$value['user_first_name'],
        $value['user_id'],$value['user_email'],$value['user_response'],
        $value['user_phone']
    );

    fputcsv($fp, $array_add);

};

fclose($fp);

header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Length: ". filesize(SITE_ROOT.$link).";");
header("Content-Disposition: attachment; filename=".$link);
header("Content-Type: application/octet-stream; "); 
header("Content-Transfer-Encoding: binary");

readfile(SITE_ROOT.$link);

unlink(SITE_ROOT.$link);
}   

Thanks in advance.

fairywings78
  • 117
  • 1
  • 8
  • Sounds like an output buffering issue. You shouldn't be mixing output formats in the one request. – Phil Apr 17 '13 at 01:06

1 Answers1

0

Adding a die(); after your call to unlink(SITE_ROOT.$link); should prevent the rest of the page from executing and thus mucking up your CSV with HTML.

George Hodgson
  • 471
  • 2
  • 12
  • thanks, that is an elegant solution, but any idea as to why the amount of html affects the output? – fairywings78 Apr 17 '13 at 04:15
  • No, I'm not sure without seeing more of the code. Is it possible that the HTML is always being appended to the CSV, but your CSV reader is only displaying it when it contains a specific character, like a comma perhaps? – George Hodgson Apr 17 '13 at 13:43