Advertisement
Guest User

CsvParser.class.php - parses CSV files

a guest
Dec 28th, 2012
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.15 KB | None | 0 0
  1. <?php
  2.  
  3. // CSV parser class
  4. // (c) 2002, Berkus
  5.  
  6. class CsvParser
  7. {
  8.    var $headers = array();
  9.    var $fields = array();
  10.    var $numRecords = 0;
  11.  
  12.    function CsvParser($file, $readHeaders = true, $delim = ",")
  13.    {
  14.       if (file_exists($file)) {
  15.          $f = fopen($file, "r");
  16.          if (!$f) { echo "Cannot read CSV file"; error_log("Cannot read CSV file ".$file, 0); return; }
  17.  
  18.          if ($readHeaders === true) {
  19.             $this->headers = $this->getcsv($f, $delim);
  20.          }
  21.  
  22.          while ($data = $this->getcsv($f, $delim)) {
  23.             $this->fields[] = $data;
  24.             $this->numRecords++;
  25.          }
  26.          fclose($f);
  27.       } else {
  28.          echo "CSV file doesn't exist";
  29.          error_log("CSV file ".$file." doesn't exist", 0);
  30.          return;
  31.       }
  32.    }
  33.  
  34.    function getcsv($fp, $delim)
  35.    {
  36.       if ($f = fgets($fp, 4096))  return explode($delim, $f);
  37.       else                        return false;
  38.    }
  39.  
  40.    function getRecord($num)
  41.    {
  42.       if ($num >= 0 && $num < $this->numRecords) return $this->fields[$num];
  43.       else                                       return array();
  44.    }
  45. };
  46.  
  47. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement