2015-05-27 13 views
3

使用fgetcsv是我發現讀取系統所需的csv文件的選項。但它似乎並不是每次都有效(實際上這種代碼工作時非常罕見)。fgetcsv將第一行中的所有數據帶入

if (($handle = fopen($file, 'r')) !== FALSE) { 
    set_time_limit(0); // necessary if a large csv file 

    $row = 0; 
    while (($data = fgetcsv($handle, 0, ',')) !== FALSE) { 
     print_r($data); 
     // .. here I do some stuff with the data 
     // .. The result should be an array with 5 columns and it run multiple times (for the amount of lines in the file) 
     // .. The result however is one array with a over 9000 columns (really over 9000, it's 9489 in the file that I'm testing) 
    } 
    fclose($handle); 
    die(); 
} 

我試圖通過在代碼之前調用它來檢查行結束,但沒有取得太大的成功。

ini_set('auto_detect_line_endings', true); 

該文件由另一個程序由客戶端導出,我不能讓它「更新」以適應軟件的需要。有什麼辦法來處理這個問題csv上的這個encoding/line-ending

+2

你看着原始文件,看看裏面有什麼了?也許它是在沒有行結束的情況下生成的,或者是完全不符合標準的結束字符。 –

回答

0

PHP Manual(我知道激進的想法)

長度參數

必須大於最長行的情況下(字符數)在CSV文件中找到(允許尾隨線端字符)。它在PHP 5中成爲可選項。省略此參數(或者在PHP 5.1.0及更高版本中將其設置爲0),最大行長度不受限制,這稍微慢一些。

我不知道你使用的是什麼版本的PHP,但嘗試設置參數是明智的,你應該開始一次獲得一行。

while (($data = fgetcsv($handle, 4096, ',')) !== FALSE) { 
相關問題