Text Downloadable Files with PHP
Posted on Jun 28, 2013
I needed to create a file which had to be downloaded.
The file had to be in plain text and contents from file come from database. Because I didn't had
a separate folder for each user I couldn't write the information to a file to the server and put a link
in order the user to download it. I even try to other formats like .xls, .doc, .csv and it works really nice.
Code for downloadable file:
Code for downloadable file:
<? header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"your_file.txt\""); echo 'Text for downloadable file'; ?>
1. Code for CSV Downloadable file
The real magic comes when you wanna make csv file downloadable. You can read data from a mysql table and write the contents to a csv file. You should only read contents from a table and using echo output to the file.<? header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"your_file.csv\""); $connect = mysql_connect($server, $user, $password) or die ("MySQL Database Connect Error"); $resultcsv = mysql_db_query($database, "select * from $csvTable"); while ($query = mysql_fetch_array($resultcsv)) { echo $query["Name"].",".$query["City"]."\n"; } mysql_close($connect); ?>
2. Code for Microsoft Excel (.xls) downloadable file
Code for generating a excel downloadble file:<? header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"your_file.xls\""); $connect = mysql_connect($server, $user, $password) or die ("MySQL Database Connect Error"); $resultxls = mysql_db_query($database, "select * from $xlsTable"); while ($query = mysql_fetch_array($resultxls)) { echo $query["Name"]."\t".$query["City"]."\n"; } mysql_close($connect); ?>
3. Code for Microsoft Word (.doc) downloadable file
You can even make a downloadable .doc files by changing the file extension to doc.<? header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"your_file.doc\""); echo 'Contents of Word Document.'; ?>
Leave a comment: