본문 바로가기
Web Program/Php Lecture

fgetcsv 를 이용한 csv 파일 읽기

by 현이빈이 2008. 9. 8.
반응형

1. 일반적 방법

/**
 * Based on an example by ramdac at ramdac dot org
 * Returns a multi-dimensional array from a CSV file optionally using the
 * first row as a header to create the underlying data as associative arrays.
 * @param string $file Filepath including filename
 * @param bool $head Use first row as header.
 * @param string $delim Specify a delimiter other than a comma.
 * @param int $len Line length to be passed to fgetcsv
 * @return array or false on failure to retrieve any rows.
 */
function importcsv($file,$head=false,$delim=",",$len=1000) {
   $return = false;
   $handle = fopen($file, "r");
   if ($head) {
       $header = fgetcsv($handle, $len, $delim);
   }
   while (($data = fgetcsv($handle, $len, $delim)) !== FALSE) {
       if ($head AND isset($header)) {
           foreach ($header as $key=>$heading) {
               $row[$heading]=(isset($data[$key])) ? $data[$key] : '';
           }
           $return[]=$row;
       } else {
           $return[]=$data;
       }
   }
   fclose($handle);
   return $return;
}

 

 

2. 클래스를 이용한 방법

 

<?php
class CsvIterator implements Iterator
{
   const ROW_SIZE = 4096;
   /**
     * The pointer to the cvs file.
     * @var resource
     * @access private
     */
   private $filePointer = null;
   /**
     * The current element, which will
     * be returned on each iteration.
     * @var array
     * @access private
     */
   private $currentElement = null;
   /**
     * The row counter.
     * @var int
     * @access private
     */
   private $rowCounter = null;
   /**
     * The delimiter for the csv file.
     * @var str
     * @access private
     */
   private $delimiter = null;

   /**
     * This is the constructor.It try to open the csv file.The method throws an exception
     * on failure.
     *
     * @access public
     * @param str $file The csv file.
     * @param str $delimiter The delimiter.
     *
     * @throws Exception
     */
   public function __construct($file, $delimiter=',')
   {
       try {
           $this->filePointer = fopen($file, 'r');
           $this->delimiter = $delimiter;
       }
       catch (Exception $e) {
           throw new Exception('The file "'.$file.'" cannot be read.');
       }
   }

   /**
     * This method resets the file pointer.
     *
     * @access public
     */
   public function rewind() {
       $this->rowCounter = 0;
       rewind($this->filePointer);
   }

   /**
     * This method returns the current csv row as a 2 dimensional array
     *
     * @access public
     * @return array The current csv row as a 2 dimensional array
     */
   public function current() {
       $this->currentElement = fgetcsv($this->filePointer, self::ROW_SIZE, $this->delimiter);
       $this->rowCounter++;
       return $this->currentElement;
   }

   /**
     * This method returns the current row number.
     *
     * @access public
     * @return int The current row number
     */
   public function key() {
       return $this->rowCounter;
   }

   /**
     * This method checks if the end of file is reached.
     *
     * @access public
     * @return boolean Returns true on EOF reached, false otherwise.
     */
   public function next() {
       return !feof($this->filePointer);
   }

   /**
     * This method checks if the next row is a valid row.
     *
     * @access public
     * @return boolean If the next row is a valid row.
     */
   public function valid() {
       if (!$this->next()) {
           fclose($this->filePointer);
           return false;
       }
       return true;
   }
}
?>

Usage :

<?php
$csvIterator = new CsvIterator('/path/to/csvfile.csv');
foreach ($csvIterator as $row => $data) {
   // do somthing with $data
}
?>

반응형