2014-01-29 54 views
-1

這是我的Csv上傳腳本如何讓它忽略我的Csv文件的前2行。 無法找到正確的方式來跳過/忽略它。 有點幫助嗎?如何跳過我的Csv文件的前2行

<?php 
    include 'connect.php'; 
    if (isset($_FILES['userfile'])) 
    { 
     $csv_file = $_FILES['userfile']['tmp_name']; 

     if (! is_file($csv_file)) 
     exit('File not found.'); 



     if (($handle = fopen($csv_file, "r")) !== FALSE) 
     { 
      while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) 
      { 
      { 
      $sql = "INSERT INTO `prelims` (`name`,`grade`) VALUES('$data[0]','$data[2]')"; 
      $exec = mysql_query($sql) or die(mysql_error());  

      echo ("The following data has been added to the database"); 
      } 
      } 
     } 
     } 
    ?> 
+0

你不能剛開始在csv的第三行迭代嗎? – jeremyjjbrown

+1

有關以前的嘗試稍加闡述?就像你有沒有試過一個計數器和'繼續',或者預先安排了兩個空的fgets/fgetcsv調用? – mario

+0

這個腳本正在工作,但我只需要跳過前兩行來完成它。 –

回答

1
fgetcsv($handle); // get line 0 and move pointer to line 1 
fgetcsv($handle); // get line 1 and move pointer to line 2 
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) 
... 

您可能還需要做一些錯誤檢查最重要的是,以確保您的CSV至少有2條線在裏面。

+0

fseek從文件的開始以字節方式工作。它不會跳過行 – freento

+0

@magalter,謝謝指出。直到現在我才意識到這一點。我已經刪除了無效的答案。 –

0

請注意,上述部分答案不正確。該行 fseek($handle, 2); 確實不是尋求前行兩行;它尋求轉發兩個字節。要跳過任意數量的行,你可以這樣做:

$skipLines = 5000; // or however many lines you want to skip 
$lineNum = 1; 
if ($skipLines > 0) { 
    while (fgetcsv($handle)) { 
     if ($lineNum==$skipLines) { break; } 
     $lineNum++; 
    } 
} 
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { 
    // starts getting data from 5001st row 
} 
相關問題