Jump to content

epxort query to csv is sending entire page source code

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
cheeseslice

cheeseslice

    Newbie

  • Members
  • Pip
  • 3 posts
Hi,

I am learning php as I go along, so this might be a pretty basic problem but I'm hoping someone can help me.

I have been asked to customise a bit of code on a wordpress website so that it exports a few fields from a table to a csv file.

I have come up with this code:


$file = 'export';


$query = "select * from " . $wpdb->prefix . "newsletter";

$recipients = $wpdb->get_results($query . " order by email");

for ($i=0; $i<count($recipients); $i++) {

$csv_output .= $recipients[$i]->email . ',' . $recipients[$i]->name . ',' . $recipients[$i]->status . ',' . $recipients[$i]->token . "\n";

}


$filename = $file."_".date("Y-m-d_H-i",time());

header("Content-type: application/vnd.ms-excel");

header("Content-disposition: csv" . date("Y-m-d") . ".csv");

header( "Content-disposition: filename=".$filename.".csv");

	

echo $csv_output;

exit;


When I open the exported csv file I get the results at the bottom of the page, unfortunately it also exports the entire html source code of the page that it is being called from too.

I have tried using print and print_r instead of echo thinking that it might have made a difference, but it doesn't.

If I run this code without the bottom lines of code to export to the file and echo the results to the screen, they are exactly as I would like them to be in the file. I don't understand why the content of the query changes once I send it to the file.

Thanks in advance

#2
cheeseslice

cheeseslice

    Newbie

  • Members
  • Pip
  • 3 posts
If I remove the echo $csv_output; the file still contains the entire source code so I assume one of the header lines is wrong, but I can't work out what it is that is actually wrong with them.

#3
cheeseslice

cheeseslice

    Newbie

  • Members
  • Pip
  • 3 posts
I have worked this out, so I'm putting up a solution just in case anyone else gets stuck with this.

ob_end_clean();

before printing to the csv was the answer. I just have to read up on why this was happening so I understand for the next time.