【问题标题】:Reduce memory usage while dumping Access table to CSV将 Access 表转储到 CSV 时减少内存使用量
【发布时间】:2015-09-09 15:04:13
【问题描述】:

我正在使用这个简单的代码来读取一个 80 MB 的 .mdb 文件并在 WAMP 环境中将其转换为 CSV,但是我遇到了令人惊讶的高内存使用率(超过 512 MB)

有什么方法可以将加载分成几部分或其他方式来避免如此高的内存使用?

$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename", $user, $password);

$qry = "SELECT * FROM data";

$result = odbc_exec($conn,$qry);

$theArray = array();

while ( ($row = odbc_fetch_array($result)) )
   {
      array_push($theArray, $row);
   }

$fp = fopen('dispo_e.csv', 'w');
foreach ($theArray as $lines) 
{
    fputcsv($fp, $lines, ";");
}

【问题讨论】:

  • 如果您喜欢任何答案,请务必投票并点击您最喜欢的(无耻自我宣传)旁边的票

标签: php csv ms-access wamp


【解决方案1】:

最简单的选择是不将其分配给数组,而是直接写入 CSV。

$conn = odbc_connect(
    "Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename",
    $user,
    $password
);

$result = odbc_exec($conn, 'SELECT * FROM data');

$fp = fopen('dispo_e.csv', 'w');
while (($row = odbc_fetch_array($result))) {
    fputcsv($fp, $lines, ';');
}

fclose($fp);

【讨论】:

    【解决方案2】:

    你可以试试这个功能(用法如下):

    <?php
        function query_to_csv($db_conn, $query, $filename, $attachment = false, $headers = true) {
    
            if($attachment) {
                // send response headers to the browser
                header( 'Content-Type: text/csv' );
                header( 'Content-Disposition: attachment;filename='.$filename);
                $fp = fopen('php://output', 'w');
            } else {
                $fp = fopen($filename, 'w');
            }
    
            $result = mysql_query($query, $db_conn) or die( mysql_error( $db_conn ) );
    
            if($headers) {
                // output header row (if at least one row exists)
                $row = mysql_fetch_assoc($result);
                if($row) {
                    fputcsv($fp, array_keys($row));
                    // reset pointer back to beginning
                    mysql_data_seek($result, 0);
                }
            }
    
            while($row = mysql_fetch_assoc($result)) {
                fputcsv($fp, $row);
            }
    
            fclose($fp);
        }
    
        // Using the function
        $sql = "SELECT * FROM table";
        // $db_conn should be a valid db handle
    
        // output as an attachment
        query_to_csv($db_conn, $sql, "test.csv", true);
    
        // output to file system
        query_to_csv($db_conn, $sql, "test.csv", false);
    ?>
    

    【讨论】:

    • 所以你只是复制了一段代码!它与OP的问题有什么关系?没有!您应该回答问题,而不是更改问题以适合您认为可能有的答案。
    猜你喜欢
    • 2021-11-09
    • 2020-01-01
    • 2012-01-20
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    相关资源
    最近更新 更多