Export MySQL table in CSV format using PHP
I recently had a project that I had to extract data from a MySQL database and produce a CSV file from it. Upon my search I found the following code to do just that.
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 |
<?php /*MySQL to CSV Export*/ /*Declare your DB Settings*/ $mysql_host = "localhost"; $mysql_user = "DB_User"; $mysql_pass = "DB_Pass"; $link = mysql_connect($mysql_host,$mysql_user,$mysql_pass) or die('Could not connect: '.mysql_error()); mysql_select_db($mysql_db,$link) or die('Could not select database: '.$mysql_db); $query = "SELECT * FROM $tablename ORDER BY id"; $result = mysql_query($query) or die("Error executing query: ".mysql_error()); $row = mysql_fetch_assoc($result); $line = ""; $comma = ""; foreach($row as $name => $value){ $line .= $comma . '"' . str_replace('"', '""', $name) . '"'; $comma = ";"; } $line .= "n"; $out = $line; mysql_data_seek($result, 0); while($row = mysql_fetch_assoc($result)){ $line = ""; $comma = ""; foreach($row as $value){ $line .= $comma . '"' . str_replace('"', '""', $value) . '"'; $comma = ";"; } $line .= "n"; $out.=$line; } header("Content-type: text/csv"); header("Content-Disposition: attachment; filename=listino.csv"); echo $out; exit; ?> |
The code was found at matteomattei.com
Recent Comments