Fix for Count rows in a large file

  1. /**
  2.  * Helper function to get the number of rows in a file. Excludes the first row
  3.  * which contains the column names.
  4.  *
  5.  * @param string $file
  6.  *      The filename. Should only be the name itself with no path info. Path
  7.  *      info will be added automatically.
  8.  * @return int
  9.  *      The number of rows in the file, or -1 if the file does not exist. Note
  10.  *      that this function might legitimately return 0 if the file is empty.
  11.  */
  12. function _tigerfish_import_get_file_rows($file) {
  13.   $filename = _tigerfish_import_filepath() . '/' . $file;
  14.    
  15.   if (file_exists($filename)) {
  16.     $handle = fopen($filename, "r");
  17.     $count = 0;
  18.    
  19.     while (fgets($handle)) {
  20.       $count++;
  21.     }
  22.        
  23.     // Subtract one to account for the first row containing column names.
  24.     return $count - 1;
  25.   }
  26.   else {
  27.     // The file does not exist!
  28.     return -1;
  29.   }
  30. }

Submit Fix

Any tags you'd like to associate with your code, delimitered by commas (example: Views, CCK, Module, etc).
Select the syntax highlighting mode to use.