php - 使用 php 将 20k 或更多记录从 MY SQL 导出到 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;
            $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

http://ariejan.net/2008/11/27/export-csv-directly-from-mysql/

关于php - 使用 php 将 20k 或更多记录从 MY SQL 导出到 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19187626/

相关文章:

generics - 如何将实例化的泛型函数导出到 C

php - 为什么我的 header ("Location: $_SERVER[' HTTP_REFERER']"); PHP 函数不起作用?

c++ - 在自定义库中操作二维 C++ 数组 - 获取行数?

Oracle expdp 无数据

PHP - 将 MySQL 表导出到 JSON 文件

xml - 解析 XML 并找到字符串的所有实例

php - 在 SQL 表中选择两个随机行,其中列的值非常接近

php - 变量中的 var_dump() 输出

PHP正则表达式的单词短语语法?

java - 从 csv 读取值并将占位符替换到模板中