2011-12-03 32 views
1

我用一個簡單的函數寫寫入陣列到CSV文件,它看起來像這樣:寫入多個(分裂)的CSV文件用PHP

function writeToCSV($array) { 
    $fp = fopen('programmes.csv', 'a'); 
    fputcsv($fp, $array); 
    fclose($fp); 
} 

簡單的餡餅。但是,無論如何要知道指針所在的行號是什麼?因爲我希望能夠在1000行之後開始寫入新文件。爲什麼?因爲我需要能夠稍後將它們導入到數據庫,並且有一些內存限制,並且使用15000行解析CSV文件是一個禁忌。

回答

3
function writeToCSV($array) { 
    $i = 1; 
    $j = 1; 
    $fp = fopen('programmes' . $j . '.csv', 'a'); 
    foreach($array as $fields) { 
     if ($i % 1000 == 0) { 
      fclose($fp); 
      $fp = fopen('programmes' . $j . '.csv', 'a'); 
      $j = $j + 1; 
     } 
     fputcsv($fp, $fields); 
     $i = $i + 1; 
    } 
    fclose($fp); 
} 
+0

呵呵,不像我腦海中描繪的那樣複雜=)這應該也是我想要的。 – Marcus

0

試試這個:

count(file('programmes.csv')); 

這會給你的行數在一個文件中。

+1

它非常緩慢的操作。 –

+0

@Shiplu噢感謝提醒我;) – Jeune

0

我還沒有試過,如果這個工程,但我會做這樣的事情:

<?php 
function writeToCSV($array) { 
    // count lines in the current file 
    $linecount = 0; 
    $fh = fopen('programmes.csv','rb') or die("ERROR OPENING DATA"); 
    while (fgets($fh) !== false) $linecount++; 
    fclose($fh); 

    $aSize = sizeof($array); 
    if (($linecount + $aSize) > 1000) { 
    // split array 
    $limit = 1000 - $linecount; 
    $a = array_slice($array, 0, $limit); 
    $b = array_slice($array, $limit); 
    // write into first file 
    $fp = fopen('programmes.csv', 'a'); 
    foreach($a as $field) fputcsv($fp, $field); 
    fclose($fp); 

    // write into second file 
    $fp = fopen('programmes2.csv', 'a'); 
    foreach($b as $field) fputcsv($fp, $field); 
    fclose($fp); 
    } else { 
    $fp = fopen('programmes.csv', 'a'); 
    $idx = 0; 
    while ($linecount < 1000) { 
     // fill the file to the 1000 lines 
     fputcsv($fp, $array[$idx]); 
     ++$linecount; 
     ++$idx; 
    } 
    fclose($fp); 

    if ($idx != $aSize) { 
     // create new file 
     $fp = fopen('programmes.csv', 'a'); 
     while ($idx< $aSize) { 
     // fill the file to the 1000 lines 
     fputcsv($fp, $array[$idx]); 
     ++$idx; 
     } 
     fclose($fp); 
    } 
    } 
} 
?>