1.10.1. Problem You want to format data as comma-separated values (CSV) so that it can be imported by a spreadsheet or database. 1.10.2. Solution Use the fputcsv( ) function to generate a CSV-formatted line from an array of data. Example 1-28 writes the data in $sales into a file. Generating comma-separated data <?php $sales = array( array('Northeast','2005-01-01','2005-02-01',12.54), array('Northwest','2005-01-01','2005-02-01',546.33), array('Southeast','2005-01-01','2005-02-01',93.26), array('Southwest','2005-01-01','2005-02-01',945.21), array('All Regions','--','--',1597.34) ); $fh = fopen('sales.csv','w') or die("Can't open sales.csv"); foreach ($sales as $sales_line) { if (fputcsv($fh, $sales_line) === false) { die("Can't write CSV line"); } } fclose($fh) or die("Can't close sales.csv"); ?> | 1.10.3. Discussion To print the CSV-formatted data instead of writing it to a file, use the special output stream php://output , as shown in Example 1-29. Printing comma-separated data <?php $sales = array( array('Northeast','2005-01-01','2005-02-01',12.54), array('Northwest','2005-01-01','2005-02-01',546.33), array('Southeast','2005-01-01','2005-02-01',93.26), array('Southwest','2005-01-01','2005-02-01',945.21), array('All Regions','--','--',1597.34) ); $fh = fopen('php://output','w'); foreach ($sales as $sales_line) { if (fputcsv($fh, $sales_line) === false) { die("Can't write CSV line"); } } fclose($fh); ?> | To put the CSV-formatted data into a string instead of printing it or writing it to a file, combine the technique in Example 1-29 with output buffering, as shown in Example 1-30. Putting comma-separated data into a string <?php $sales = array( array('Northeast','2005-01-01','2005-02-01',12.54), array('Northwest','2005-01-01','2005-02-01',546.33), array('Southeast','2005-01-01','2005-02-01',93.26), array('Southwest','2005-01-01','2005-02-01',945.21), array('All Regions','--','--',1597.34) ); ob_start(); $fh = fopen('php://output','w') or die("Can't open php://output"); foreach ($sales as $sales_line) { if (fputcsv($fh, $sales_line) === false) { die("Can't write CSV line"); } } fclose($fh) or die("Can't close php://output"); $output = ob_get_contents(); ob_end_clean(); ?> | 1.10.4. See Also Documentation on fputcsv( ) at http://www.php.net/fputcsv; Recipe 8.12 more information about output buffering. |