2010-12-10 31 views
4

我無法獲得我寫過的新代碼來跳過第一行(標題),因爲我以前使用的代碼(參見下文)。如何在我的while循環中使用fgetcsv跳過標題行?

我沒有收到任何錯誤,但只是無法讓它省略第一行。

$file = fopen($uploadcsv,"r"); 
$column_headers = array(); 
$row_count = 0; 
while(!feof($file)) { 
    if ($row_count==0){ 
    $column_headers = $file; 
    } else { 
    print_r(fgetcsv($file)); 
    } 
    ++$row_count; 
    } 

fclose($file); 

下面是跳過標題的舊來源,供參考和比較。

$handle = fopen($uploadcsv, 'r'); 
$column_headers = array(); 
$row_count = 0; 
while (($data = fgetcsv($handle, 100000, ",")) !== FALSE) { 
    if ($row_count==0){ 
    $column_headers = $data; 
    } else { 
    print_r($data); 
    } 
    ++$row_count; 
} 
fclose($handle); 

回答

9

爲什麼要算數?只需在循環之前獲取標題即可。

$column_headers = fgetcsv($file); 
while(!feof($file)) { 
    ... 

此外,您只是將文件指針分配給變量。

+0

請解釋一下?所以不要使用$ row_count == 0?我將需要將其分配給數組$ – acctman 2010-12-10 15:09:45

+0

您決定讓我們驚訝的是什麼「$ data」? – 2010-12-10 15:12:24

+0

哦,我很抱歉,如果你看看編碼頂部(舊編碼),我使用數據$數據 – acctman 2010-12-10 16:03:15

2

$row_count0你不是閱讀任何行。

變化

if ($row_count==0){ 
    $column_headers = $file; // just assigning file handle. 
} 

if ($row_count==0){ 
    $column_headers = fgetcsv($file); // read the row. 
} 
+0

如何重寫列標題檢測當前的方式是給出一個空白輸出 – acctman 2010-12-10 20:43:34