문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top