使用php将20k或更多记录从我的SQL导出到CSV
我正试图将大约20k条记录从mysql中的一个表导出到csv,正如预期的那样,它会使我的系统崩溃,有没有其他方法可以避免崩溃 这是我当前的导出代码:使用php将20k或更多记录从我的SQL导出到CSV,php,csv,export,export-to-csv,Php,Csv,Export,Export To Csv,我正试图将大约20k条记录从mysql中的一个表导出到csv,正如预期的那样,它会使我的系统崩溃,有没有其他方法可以避免崩溃 这是我当前的导出代码: $filename2 = "csv/leads_".date("M-d-Y",time()).".csv"; $fp2 = fopen($filename2, 'w') or die("can't open file"); $sql2 = $sql_getcustomers;
$filename2 = "csv/leads_".date("M-d-Y",time()).".csv";
$fp2 = fopen($filename2, 'w') or die("can't open file");
$sql2 = $sql_getcustomers;
$res2 = mysql_query($sql2);
// fetch a row and write the column names out to the file
$row2 = mysql_fetch_assoc($res2);
$line = "";
$comma = "";
if($row2){
foreach($row2 as $name => $value) {
$line .= $comma . '"' . str_replace('"', '""', $name) . '"';
$comma = ",";
}
$line .= ",crm_group";
$line .= "\n";
fwrite($fp2, $line);
// remove the result pointer back to the start
mysql_data_seek($res2, 0);
// and loop through the actual data
while($row2 = mysql_fetch_assoc($res2)) {
$line = "";
$comma = "";
foreach($row2 as $index => $value) {
$line .= $comma . '"' . str_replace('"', '""', utf8_decode($value)) . '"';
$comma = ",";
}
//** GET THE CRM GROUPS
$sql_get_group = "SELECT a.crm_group_name, b.* FROM tbl_crm_members b JOIN tbl_crm_groups a ON (a.crm_gid = b.crm_groupid) WHERE crm_uid = ".$row2["uid"];
$sql_get_groups = mysql_query($sql_get_group);
$res_get_groups = "";
while($sgg = mysql_fetch_object($sql_get_groups)) $res_get_groups .= $sgg->crm_group_name.";";
$line .= ",".trim($res_get_groups, ";");
$line .= "\n";
fwrite($fp2, $line);
}
fclose($fp2);
为什么不让mysql来做呢
SELECT id, name, email INTO OUTFILE '/tmp/result.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM users WHERE 1
请您为我总结一下语法和工作原理。谢谢将所选数据导出到/tmp/folder(*nix)中名为result.csv的文件中。字段之间的块,并以格式化csv文件的配置终止。你可以阅读更多关于它的内容。我认为在这里重写没有意义。我能让它自动下载文件吗?不,它将文件存储在运行mysql的机器上。您可以通过php或Web服务器或ftp/scp将其作为静态文件提供。查看php.trusted,尽管我在mysql中被拒绝访问