note 104980 added to function.fputcsv

From: Date: Wed, 20 Jul 2011 13:05:18 +0000
Subject: note 104980 added to function.fputcsv
Groups: php.notes 
Request: Send a blank email to php-notes+get-181716@lists.php.net to get a copy of this message
Utility function to output a mysql query to csv with the option to write to file or send back to the browser as a csv attachment. <?php function query_to_csv($db_conn, $query, $filename, $attachment = false, $headers = true) { if($attachment) { // send response headers to the browser header( 'Content-Type: text/csv' ); header( 'Content-Disposition: attachment;filename='.$filename); $fp = fopen('php://output', 'w'); } else { $fp = fopen($filename, 'w'); } $result = mysql_query($query, $db_conn) or die( mysql_error( $db_conn ) ); if($headers) { // output header row (if at least one row exists) $row = mysql_fetch_assoc($result); if($row) { fputcsv($fp, array_keys($row)); // reset pointer back to beginning mysql_data_seek($result, 0); } } while($row = mysql_fetch_assoc($result)) { fputcsv($fp, $row); } fclose($fp); } // Using the function $sql = "SELECT * FROM table"; // $db_conn should be a valid db handle // output as an attachment query_to_csv($db_conn, $sql, "test.csv", true); // output to file system query_to_csv($db_conn, $sql, "test.csv", false); ?> ---- Server IP: 69.147.83.197 Probable Submitter: 212.9.28.176 ---- Manual Page -- http://www.php.net/manual/en/function.fputcsv.php Edit -- https://master.php.net/note/edit/104980 Del: integrated -- https://master.php.net/note/delete/104980/integrated Del: useless -- https://master.php.net/note/delete/104980/useless Del: bad code -- https://master.php.net/note/delete/104980/bad+code Del: spam -- https://master.php.net/note/delete/104980/spam Del: non-english -- https://master.php.net/note/delete/104980/non-english Del: in docs -- https://master.php.net/note/delete/104980/in+docs Del: other reasons-- https://master.php.net/note/delete/104980 Reject -- https://master.php.net/note/reject/104980 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#181716) next »