CSV-файлы очень популярны для представления электронных таблиц – файл является текстовым, ячейки таблицы в нём разделяются точкой с запятой. Представляем вашему вниманию класс, разработанный Кондраковым Александром Владимировичем, позволяющий генерировать CSV-файл из массива PHP.
Генерация CSV-файла
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
<?php class CsvReader { private $file; private $delimiter; private $length; private $handle; private $csvArray; public function __construct($file, $delimiter=";", $length = 8000) { $this->file = $file; $this->length = $length; $this->delimiter = $delimiter; $this->FileOpen(); } public function __destruct() { $this->FileClose(); } public function GetCsv() { $this->SetCsv(); if(is_array($this->csvArray)) return $this->csvArray; } private function SetCsv() { if($this->GetSize()) { while (($data = @fgetcsv($this->handle, $this->length, $this->delimiter)) !== FALSE) { $this->csvArray[] = $data; } } } private function FileOpen() { $this->handle=($this->IsFile())?fopen($this->file, 'r'):null; } private function FileClose() { if($this->handle) @fclose($this->handle); } private function GetSize() { if($this->IsFile()) return (filesize($this->file)); else return false; } private function IsFile() { if(is_file($this->file) && file_exists($this->file)) return true; else return false; } } class CsvWriter { private $file; private $delimiter; private $array; private $handle; public function __construct($file, $array, $delimiter=";") { $this->file = $file; $this->array = $array; $this->delimiter = $delimiter; $this->FileOpen(); } public function __destruct() { $this->FileClose(); } public function GetCsv() { $this->SetCsv(); } private function IsWritable() { if(is_writable($this->file)) return true; else return false; } private function SetCsv() { if($this->IsWritable()) { $content = ""; foreach($this->array as $ar) { $content .= implode($this->delimiter, $ar); $content .= "\r\n"; } if (fwrite($this->handle, $content) === FALSE) exit; } } private function FileOpen() { $this->handle=fopen($this->file, 'w+'); } private function FileClose() { if($this->handle) @fclose($this->handle); } } $array = array(array('1','1','1'), array('2','2','2'), array('3','3','3')); $dd = new CsvWriter('test.txt',$array); $dd->GetCsv(); ?> |