/csvparser.php Secret
Created
May 1, 2021 23:13
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class CsvParser | |
{ | |
protected $handle; | |
protected $header; | |
public function open($file, $header = true) | |
{ | |
$this->handle = fopen($file, 'r'); | |
if (!$this->handle) | |
{ | |
throw new RuntimeException('Файл недоступен для чтения ' . $file); | |
} | |
if ($header) | |
{ | |
$this->header = fgetcsv($this->handle); | |
} | |
return $this; | |
} | |
public function parse() | |
{ | |
$arData = []; | |
if (!$this->handle) | |
{ | |
throw new RuntimeException('Файл не открыт!'); | |
} | |
while (($data = fgetcsv($this->handle)) !== false) | |
{ | |
if ($this->header) | |
{ | |
$data = array_combine($this->header, $data); | |
} | |
$arData[] = $data; | |
} | |
return $arData; | |
} | |
public function __destruct() | |
{ | |
$this->close(); | |
} | |
public function close() | |
{ | |
if ($this->handle) | |
{ | |
fclose($this->handle); | |
$this->handle = null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment