SoFunction
Updated on 2025-02-28

PHP code examples that read and process larger CSV files by line


/**
* csv_get_lines Read a few lines of data in a CSV file
* @param $csvfile csv file path
* @param $lines Read the number of rows
* @param $offset Starting line count
 * @return array
 * */
function csv_get_lines($csvfile, $lines, $offset = 0) {
    if(!$fp = fopen($csvfile, 'r')) {
     return false;
    }
    $i = $j = 0;
 while (false !== ($line = fgets($fp))) {
  if($i++ < $offset) {
   continue;
  }
  break;
 }
 $data = array();
 while(($j++ < $lines) && !feof($fp)) {
  $data[] = fgetcsv($fp);
 }
 fclose($fp);
    return $data;
}