This article illustrates how PHP uses the specified encoding to export MySQL data to a CSV file. Share to everyone for your reference. The implementation method is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
<?php * * PHP code to export MySQL data to CSV * * Sends the result of a MySQL query as a CSV file for download * Easy to convert to UTF-8. * * /* Establish database connection */ $conn = mysql_connect (' localhost ', ' login ', ' pass ') or Die (mysql_er Ror ()); mysql_select_db (' database_name ', $conn) or Die (Mysql_error ($conn)); mysql_query ("SET NAMES CP1252"); /* Execute SQL QUERY * * * * $query = sprintf (' SELECT field1,field2 from table_name '); $result = mysql_query ($query, $conn) or Die (Mysql_error ($conn)); * * Send response headers to the browser * Following headers instruct the browser to treat the data as a CSV file called Export.csv * * Header (' content-type:text/csv; charset=cp1252 ');Header (' content-disposition:attachment;filename=output.csv '); /* Output header row (if atleast one row exists) */ $row = MYSQL_FETCH_ASSOC ($result); if ($row) {echocsv (Array_keys ($row));} * * Output data rows (if atleast one row exists)/while ($row) {Echocs V ($row); $row = Mysql_fetch_assoc ($result); * * echo the input array as CSV data maintaining consistency with most CSV implementations *-Uses double-quote s as enclosure when necessary *-uses double double-quotes to escape double-quotes *-Uses CRLF as a line separator/& nbsp function Echocsv ($fields) {$separator = '; foreach ($fields as $field) {if Preg_match ('/r|n|,| ' /', $field)) {$field = ' "'. Str_replace (', ', ' "', $field). '" ';} Echo $separator. $field; $separator = ', '; } echo "RN"; }?> |