Page 1 of 1

export from mysql table to a downloadable text file

Posted: Mon Sep 09, 2002 6:06 am
by noguru
Hi

How can I create a delimited text file from a mysql table, so that the user gets prompted to download this file? Let me explain it better: The user clicks a "download text file" button, php then creates a text file from a mysql table, using a specific sql statement such as "SELECT * FROM tbl1 WHERE usrid=1". This gets converted to a comma-delimited text file and the user gets prompted to open/save this file on his computer.

I'm sure there's some kind of mysqldump function in php, but I can't find anything.

Thanks

Posted: Mon Sep 09, 2002 6:19 am
by Coco
theres probably a nifty way to do this, but me being a newb...
write the result to your file row by row, and then do a string replace on the file?
i dont know the file commands (havent bothered to learn them yet) but a line like:

$file = str_replace(',', '', $file);

im assuming there is an easier way to do it but that _should_ work

Posted: Mon Sep 09, 2002 8:03 am
by noguru
i've managed to read my table contents into a text file, but now instead of displaying the actual page that creates this text file in the browser, i want a download prompt to appear, the same as when you href a zip file or exe.

the action must happen as i explained here above: the user clicks a "download" button, the text file gets created and then immediately the user gets a prompt to download, without loading this page in the browser. i remember in asp you could set the content type to some bixarre type other than text and then you would be prompted for download instead of loading the page in the browser.

Heather

Posted: Mon Sep 09, 2002 10:22 am
by AVATAr
After you create de file.. return a header so de Navigator prompt to download it..

something like this:

Code: Select all

header("Content-type: application/octet-stream"); 
header("Content-Length: ".$filesize); 
header("Content-Disposition: attachment; filename=".$filename); 
header("Content-Transfer-Encoding: binary");
http://www.devnetwork.net/forums/viewto ... r+download

Good Luck

Posted: Mon Sep 09, 2002 11:31 am
by Takuma

Code: Select all

<?php

  mysql_connect("localhost","user","password");
  mysql_select_db("db");

  $sql = "SELECT text FROM table WHERE id = '".$_POSTї"id"]."'";
  $result = mysql_query($sql);
  $text = mysql_fetch_array($result);

  $fh = fopen("{$_POSTї'usr']}.txt","w");
  $fwrite($text,$fh);
  $file_size = filesize($fh);
  fclose($fh);

  header("Content-type: application/octet-stream"); 
  header("Content-Length: ".$file_size); 
  header("Content-Disposition: attachment; filename=".$_POSTї'usr'].".txt"); 
  header("Content-Transfer-Encoding: binary"); 
?>

Posted: Tue Sep 10, 2002 3:30 am
by noguru
thnx for all the help guys! it's finally working! :lol: