在 PHP 中跳过 CSV 的前 3 行

  • 本文关键字:的前 CSV PHP php csv
  • 更新时间 :
  • 英文 :


我有一个readCSV函数,现在跳过第一行,但我需要它跳过前三行。

实现这一目标的首选方法是什么?

function readCSV($csvFile){
   $file_handle = fopen($csvFile, 'r');
   while (!feof($file_handle) ) {
     $array = fgetcsv($file_handle, 'r', ';');
     $line_of_text[] = array('dato'=>$array[0],'vs'=>trim($array[1]),'vf'=>trim($array[2]));
   }
   fclose($file_handle);
   return $line_of_text;
 }
$csvFile = 'http://some.file.csv';

使用计数器跟踪主页 已处理许多行:

  function readCSV($csvFile){
   $file_handle = fopen($csvFile, 'r');
   $counter = 0;
   while (!feof($file_handle) ) {
    if($counter < 3){
         $array = fgetcsv($file_handle, 'r', ';');
         $line_of_text[] = array('dato'=>$array[0],'vs'=>trim($array[1]),'vf'=>trim($array[2]));
    }
    $counter++
   }
   fclose($file_handle);
   return $line_of_text;
 }

保留一个计数器来计算循环内处理的行,仅在计数器大于 3 时才起作用。

例:

function readCSV($csvFile){
  $counter = 0;
  $file_handle = fopen($csvFile, 'r');
  while (!feof($file_handle) ) {
    if($counter > 3){
      $array = fgetcsv($file_handle, 'r', ';');
      $line_of_text[] = array('dato'=>$array[0],'vs'=>trim($array[1]),'vf'=>trim($array[2]));
    }
    $counter++;
  }
  fclose($file_handle);
  return $line_of_text;
}
$csvFile = 'http://some.file.csv';

最新更新