Export data to text file and force download

Hi all.

I need to create a “report” for my site which would work like this:

  1. my site would have a link to www.mysite.com/export.php
  2. this will just retrieve some fields from the database where ‘status=2’. These 2 steps are easy.
  3. now I want to write those fields to a text file as:

field1 | field2 | field3
field1 | field2 | field3

  1. and finally I would like the “Save As” box to be displayed right after the user clicks on the link and the export is done.

Any ideas on this?
Thanks a lot and Happy New Year to all.

For part three, you can do something like:

while($row = mysql_fetch_assoc($res))
    foreach($row as $val)
        $output .= "$value | ";
    $output = ereg_replace(" | \\$", "\
", $output); //cleans up last pipe

Then for part 4, output headers that will make the browser display “Save As…”:

// We'll be outputting a text file
header('Content-type: text/plain');

// It will be called report.txt
header('Content-Disposition: attachment; filename="report.txt"');