2013-12-22 45 views
3

我需要從大型CSV文件中讀取兩列。該CSV有多個列,並且有時可有以下特性:從PHP中的大型CSV文件讀取多列

  1. 〜了25,000行
  2. 包含空格和空行
  3. 不均勻(一些列比別人更長)

enter image description here

在上面的示例CSV文件中,我只會對「買入」和「賣出」列中的代碼感興趣(列A和D)。

我已經編寫了下面的代碼(警告:它不是很優雅)遍歷所有行並只讀取我需要的列。我爲1個大的MYSQL查詢創建字符串作爲輸入(而不是運行許多小的查詢)。

<?php 
//Increase the allowed execution time 
set_time_limit(0); 
ini_set('memory_limit','256M'); 
ini_set('max_execution_time', 0);  

//Set to detect the ending of CSV files 
ini_set('auto_detect_line_endings', true); 

$file = "test.csv"; 

$buy = $sold = ""; //Initialize empty strings 

if (($handle = @fopen($file, "r")) !== FALSE) { 

while (($pieces = fgetcsv($handle, 100, ",")) !== FALSE) {  

if (! empty($pieces[0])) { 
    $buy .= $pieces[0] ." "; 
} 

if (! empty($pieces[3])) { 
    $sold .= $pieces[3] ." "; 
} 
} 

echo "Buy ". $buy ."<br>"; //Do something with strings... 
echo "Sold ". $sold ."<br>"; 

//Close the file 
fclose($handle); 
} 

>

我的問題是:這是執行這一任務的最好方法是什麼?該代碼適用於較小的測試文件,但是在迭代通過CSV文件進行迭代時,我忽略了哪些短缺事件?

回答

1

首先,如果將任何大文件存儲在變量中,讀取任何大文件都會耗費內存。可以簽出reading large files(more than 4GB in unix)

其次,可以輸出$購買& $在while循環,這可能是更多的內存中,這兩個變量不會被保存在內存的方式高效出售 。

最後,在php中使用文件查找方法fseek documentation