Exporting to a CSV (comma-separated values) or TSV (tab-separated values) file with PHP is relatively simple with the combined use of:
- Content headers
- Formatted Printing
Below, I'll show you an example which combines the two elements above with a database query:
Notes:
- Notice the format in printf. We're using %s to represent a string, and \t as an escape character to represent a TAB
- We're assuming that you've already setup a database connection with mysql_connect.
<?php
header("Content-Disposition: attachment; filename=\"quotes.tsv\"");
header("Content-Type: text/tab-delimited-values");
$sql = "SELECT
client,
address,
city,
state,
postal,
phone,
email
FROM quote";
$res = mysql_query($sql, $connection)
echo "Client\tAddress\tCity\tState\tZip\tPhone\tE-Mail\n";
while ($row = mysql_fetch_array($res)) {
printf("%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
$row['client'],
$row['address'],
$row['city'],
$row['state'],
$row['postal'],
$row['phone'],
$row['email'],
);
}
?>