Home >Backend Development >PHP Tutorial >How to export mysql data to csv file using specified encoding_PHP tutorial
This article describes the method of exporting mysql data to a csv file in php using the specified encoding. Share it with everyone for your reference. The specific implementation method is as follows:
|
<๐>/*<๐> <๐>* 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_error());<๐> <๐>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) {<๐> <๐>echocsv($row);<๐> <๐>$row = mysql_fetch_assoc($result);<๐> <๐>}<๐> <๐> <๐> <๐>/*<๐> <๐>* echo the input array as csv data maintaining consistency with most CSV implementations<๐> <๐>* - uses double-quotes as enclosure when necessary<๐> <๐>* - uses double double-quotes to escape double-quotes<๐> <๐>* - uses CRLF as a line separator<๐> <๐>*/<๐> <๐> <๐> <๐>function echocsv($fields)<๐> <๐>{<๐> <๐>$separator = '';<๐> <๐>foreach ($fields as $field) {<๐> <๐>if (preg_match('/\r|\n|,|"/', $field)) {<๐> <๐>$field = '"' . str_replace('"', '""', $field) . '"';<๐> <๐>}<๐> <๐>echo $separator . $field;<๐> <๐>$separator = ',';<๐> <๐>}<๐> <๐>echo "rn";<๐> <๐>}<๐> <๐>?> |