class TsvParce
{
private $totals;
private $data;
private $headers;
private $str;
public function __construct($str)
{
$this->str = $str;
$this->parce();
return $this;
}
public function getTotal()
{
return $this->totals;
}
public function getData()
{
return $this->data;
}
public function getHeaders()
{
return $this->headers;
}
public function parce()
{
if (!$this->str || strlen($this->str) < 10) {
return $this;
}
$lines = explode(PHP_EOL, $this->str);
$count = count($lines);
$lastLine = $count - 2;
$totalLine = $lines[$lastLine];
$this->parceTotal($totalLine);
$this->headers = explode("\t", $lines[1]);
unset($lines[0], $lines[1], $lines[$lastLine], $lines[$count - 1]);
if (count($this->headers) > 0) {
$this->parceData($lines);
}
return $this;
}
private function parceData($lines)
{
$countHeader = count($this->headers);
$data = [];
foreach ($lines as $line) {
$row = explode("\t", $line);
if (count($row) == $countHeader) {
$data[] = array_combine($this->headers, $row);
}
}
$this->data = $data;
}
private function parceTotal($line)
{
if (preg_match('/Total rows: (\d+)/', $line, $match)) {
$this->totals = $match[1];
}
}
}
//Пример использования
$tsv = new TsvParce($data);
print_r($tsv->getTotal());
print_r($tsv->getHeaders());
print_r($tsv->getData());