Log in

View Full Version : Problem with script thats supposed to export to CSV



camrinp
12-19-2010, 04:42 PM
Hi all,

I am having a problem with my script where when i try to export data from my database to a csv file it appends the html of the page to the bottom of the CSV file. It gives me all the necessary values I need, but with annoying html of the page at the end. I am not sure how to get past this issue so some tips would be appreciated. The code is as follows.




case "csv":
$main .= "<h1>Export to CSV Format</h1>";
$main .= '<div class="orange_container">';

$sql = "SELECT id,date,fullname,street,city,zip,phone,email,club FROM registration";
$results = $db->qarray($sql);
//
// send response headers to the browser
// following headers instruct the browser to treat the data as a csv file called export.csv
//
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename=export.csv' );
//
// output header row (if atleast one row exists)
//

if($results != false)
{
foreach($results as $result)
{
$fields = array($result['id'],$result['date'],$result['fullname'],$result['street'],$result['city'],$result['zip'],$result['phone'],$result['email'],$result['club']);
echocsv($fields);

}
$main .= "CSV File created!";
}
else
{
$main .= '<div id="error">Failed to create CSV File!</div>';
}

$main .= '</div>';
break;

Schmoopy
12-19-2010, 05:53 PM
I'd need to see more of the code, but I imagine you're echoing $main somewhere, after the switch statement.

You've put the header as a CSV file, so any content will be included in it, even the HTML you write afterwards. I'd also need to see what "echocsv" does. But you want to separate the code that creates the CSV, and the code that outputs that the CSV file was created.

Maybe try using a redirect after the CSV has been created.

camrinp
12-19-2010, 06:25 PM
I have attached the file as a zip for you to look at the code.

camrinp
12-19-2010, 06:27 PM
Sorrry forgot the file last post

camrinp
12-19-2010, 09:35 PM
Anyone have any ideas ? This is driving me nuts!