Export MySql Into CSV

After examine the different between XML and CSV file, I found out that when you export a database to XML and CSV files, the CSV file should be smaller than the XML file. Therefore, in this article I will explain about how to Export MySql Into CSV.

This article is a little bit simillar with my previous post about Export MySql Into XML. The different is we will use CSV this time.

$host = 'localhost';//host name, in this case we use localhost
$user = 'root';//user name, in this case we use root
$pass = 'password';//password, in this case we use password
$db = 'member';//declare the database that will be used
$table = 'tos';//table that will be exported
$file = 'export';

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");

$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_array($values)) {
	foreach($rowr as $key => $val){
		if (!preg_match('#^\d+$#', $key, $match)){
			$csv_output .= '"'.$val.'";';
		}
	}
	$csv_output = rtrim($csv_output, ";");
	$csv_output .= "\n";
}

$filename = $file."-".$db."-".$table."_".date("Y-m-d_H:i:s",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
echo $csv_output;
exit;

When the file is executed, the file will generate an CSV file. I will post how to import database from an CSV file next time. Hope this simple article can help you alot.

http://septiadi.com/2011/05/30/export-mysql-into-csv/

Advertisements

One response to “Export MySql Into CSV

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: