Home

Saturday, August 18, 2012

Export Mysql data to CSV with PHP


<?php
$database="wordpress";
$table="wp_member";
mysql_connect("localhost","root","");
mysql_select_db("wordpress");
$result = mysql_query("SELECT * FROM wp_member");

$out = '';

// Get all fields names in table "wp_member" in database "wordpress".
$fields = mysql_list_fields($database,$table);

// Count the table fields and put the value into $columns.
$columns = mysql_num_fields($fields);

// Put the name of all fields to $out.
for ($i = 0; $i < $columns; $i++) {
$l=mysql_field_name($fields, $i);
$out .= '"'.$l.'",';
}
$out .="\n";

// Add all values in the table to $out.
while ($l = mysql_fetch_array($result)) {
for ($i = 0; $i < $columns; $i++) {
$out .='"'.$l["$i"].'",';
}
$out .="\n";
}

// Open file export.csv.
$f = fopen ('export.csv','w');

// Put all values from $out to export.csv.
fputs($f, $out);
fclose($f);

header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="export.csv"');
readfile('export.csv');
?>

No comments:

Post a Comment

rathoddhirendra.blogspot.com-Google pagerank and Worth