News and Views
Saturday, October 13, 2007 10:18:02 AM
I dug up an old PHP class that I wrote a few years back and thought I would post it for anyone who needs CSV functionality on their site. It will work with any PHP recordset, including Cartweaver recordsets, which use my custom DB abstraction class (only for MySQL, though). The CSVFile class is simple, and can be downloaded here.
The class is typically used on a page by itself, or on any page within conditional statements. You link to the page and the file download begins. The class constructor has 3 arguments:
$csvfile = new CSVFile(recordsetName, [quotes true or false], [filename]);
The first is the MySQL recordset. The second optional argument is true or false to put quotes around the fields. The third optional argument is the filename, which defaults to Download.csv by default.
To use it, follow these instructions:
1. If this is a Cartweaver recordset, make sure you include the application.php file at the top of the page:
2. Include the class file:
3. Create your recordset. Below is a typical Dreamweaver recordset, using the Northwind database that you can download here for MySQL if you don't have it:
$query_rs = "SELECT p.ProductID, p.ProductName, p.UnitPrice FROM products p ORDER BY p.ProductID";
$rs = mysql_query($query_limit_rs, $connNorthwind) or die(mysql_error());
For Cartweaver, a typical recordset might look like this:
$query_rs = "SELECT * FROM tbl_orders ORDER BY order_Date";
$rs = $cartweaver->db->executeQuery($query_rs, "rs");
4. Add a line to invoke the CSVFile class:
$csvfile = new CSVFile($rs, true);
5. Link to the file.
Now, when the page is browsed, the file download will begin immediately.
Before posting comments or trackbacks, please read the posting policy.