Esportare una tabella MySQL in formato CSV utilizzando PHP
Inviato da Matteo Mattei ~ 30th luglio 2011
Il seguente codice PHP può essere utilizzato per exportare una tabella MySQL in formato CSV e quindi facilmente modificabile con MS Excel.
$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;
That seems to be a pretty standard approach, but I think it’s better to use fgetcsv() which automatically handles quoting and separators for you. It results in less code, is faster (since its underlying implementation is in C), there’s less chance of incorrect quoting, etc. My colleague Daniel Cousineau wrote about this same topic you might like to read. http://www.toosweettobesour.com/2008/10/10/outputting-csv-as-a-downloadable-file-in-php/