2014-01-29 55 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 
} 
相关问题