"a259784,259785 (2017-03-19 - 2018-03-19)"
AdGroupName Impressions Clicks Cost
Группа №2952489 10905034 939944 575118050000
Группа №2952490 10976444 944645 576994320000
Группа №2952491 10926208 947145 580294830000
Группа №2952492 10851243 945256 574691690000
Группа №2952493 10844346 946921 578424030000
Total rows: 5
'AdGroupName' => 'Группа №2952489' , Impressions => '10905034', ........
$str = preg_replace("/Total rows:(.*)/", "", $str);
$str = explode("\n", $str) ;
unset($str[0]);
unset($str[1]);
foreach($str as $line){
if(!empty($line)){
list($gn, $imp, $cl, $coast) = explode("\t", $line);
$linearray = array(
"AdGroupName" => $gn,
"Imp" => $imp,
"clicks" => $cl,
"coast" => $coast,
);
print_R($linearray);
}
};
$str = "
Группа №2952489 10905034 939944 575118050000
Группа №2952490 10976444 944645 576994320000
Группа №2952491 10926208 947145 580294830000
Группа №2952492 10851243 945256 574691690000
Группа №2952493 10844346 946921 578424030000
";
foreach( explode("\n", $str) as $line ){
list($gn, $imp, $cl, $coast) = explode("\t", $line);
$linearray = array(
"AdGroupName" => $gn,
"Imp" => $imp,
"clicks" => $cl,
"coast" => $coast,
);
};
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());