1 <?php
2
3 4 5 6 7 8 9 10
11
12 namespace Grido\Components;
13
14 15 16 17 18 19 20
21 class Export extends Component implements \Nette\Application\IResponse
22 {
23 const ID = 'export';
24
25 26 27 28
29 public function __construct(\Grido\Grid $grid, $label = NULL)
30 {
31 $this->grid = $grid;
32 $this->label = $label === NULL
33 ? ucfirst($this->grid->getName())
34 : $label;
35
36 $grid->addComponent($this, self::ID);
37 }
38
39 40 41 42 43
44 protected function generateCsv($data, \Nette\ComponentModel\RecursiveComponentIterator $columns)
45 {
46 $head = array();
47 foreach ($columns as $column) {
48 $head[] = $column->getLabel();
49 }
50
51 $resource = fopen('php://temp/maxmemory:' . (5 * 1024 * 1024), 'r+');
52 fputcsv($resource, $head);
53
54 foreach ($data as $item) {
55 $items = array();
56 foreach ($columns as $column) {
57 $items[] = $column->renderExport($item);
58 }
59
60 fputcsv($resource, $items);
61 }
62
63 rewind($resource);
64 $output = stream_get_contents($resource);
65 fclose($resource);
66
67 return $output;
68 }
69
70 71 72
73 public function handleExport()
74 {
75 $this->grid->onRegistered && $this->grid->onRegistered($this->grid);
76 $this->grid->presenter->sendResponse($this);
77 }
78
79
80
81 82 83 84 85 86
87 public function send(\Nette\Http\IRequest $httpRequest, \Nette\Http\IResponse $httpResponse)
88 {
89 $file = $this->label . '.csv';
90 $data = $this->grid->getData(FALSE);
91 $columns = $this->grid[\Grido\Components\Columns\Column::ID]->getComponents();
92 $source = $this->generateCsv($data, $columns);
93
94 $charset = 'UTF-16LE';
95 $source = mb_convert_encoding($source, $charset, 'UTF-8');
96 $source = "\xFF\xFE" . $source;
97
98 $httpResponse->setHeader('Content-Encoding', $charset);
99 $httpResponse->setHeader('Content-Length', strlen($source));
100 $httpResponse->setHeader('Content-Type', "text/csv; charset=$charset");
101 $httpResponse->setHeader('Content-Disposition', "attachment; filename=\"$file\"; filename*=utf-8''$file");
102
103 print $source;
104 }
105 }
106