Skip to content

Instantly share code, notes, and snippets.

@web-masterok
Created May 1, 2021 23:13
<?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