Exporting to CSV or TSV with PHP

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'],
            );
   
}

?>

Posted in PHP | Tagged , | 2 Comments

ColdFusion PDF Exports

ColdFusion 7 and up makes it extremely easy to generate PDFs on the fly using the CFDocument tag, but it only offers the option of saving to a file, or streaming to the browser. If you want additional control, combine CFDocument with CFHeader as follows:

<cfcontent type="application/pdf">
<cfheader name="Content-Disposition" value="attachment;filename=export.pdf">

<cfdocument format="PDF">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title>Hello World</title>
</head>
<body>

    Hello World

</body>
</html>
</cfdocument>

Posted in ColdFusion | Tagged | 1 Comment

ColdFusion CFZip file permissions

Those familiar with the CFZip tag know that it doesn't offer the "mode" attribute as CFFile does. This presents a problem when storing a zip file on the file system, especially when the need arises to overwrite that zip file. The solution we've come up with is to first use CFFile to create an empty file, and make it writeable.

<cffile action="write" file="#mypath#/#myfile#.zip" output=" " mode="777">

<cfzip file="#mypath#/#myfile#.zip" action="zip" overwrite="true">

Posted in ColdFusion | Tagged , | Leave a comment