1. Go to this page and download the library: Download kongka/cakephp-csvview library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
// In your routes.php file:
Router::extensions('csv');
// In your controller:
public $components = [
'RequestHandler' => [
'viewClassMap' => ['csv' => 'CsvView.Csv']
]
];
public function export()
{
$posts = $this->Post->find('all');
$this->set(compact('post'));
if ($this->request->params['_ext'] === 'csv') {
$_serialize = 'posts';
$_header = array('Post ID', 'Title', 'Created');
$_extract = array('id', 'title', 'created');
$this->set(compact('_serialize', '_header', '_extract'));
}
}
// View used will be in src/Template/Posts/csv/export.ctp
public function export()
{
$posts = $this->Post->find('all');
$_serialize = null;
$this->viewBuilder()->setClassName('CsvView.Csv');
$this->set(compact('posts', '_serialize'));
}
$this->set('_extension', 'mbstring');
public function export()
{
$data = [
['a', 'b', 'c'],
[1, 2, 3],
['you', 'and', 'me'],
];
$_serialize = 'data';
$this->response = $this->response->withDownload('my_file.csv'); // <= setting the file name
$this->viewBuilder()->setClassName('CsvView.Csv');
$this->set(compact('data', '_serialize'));
}
use Cake\View\View;
use Cake\View\ViewBuilder;
// Your data array
$data = [];
// Params
$_serialize = 'data';
$_delimiter = ',';
$_enclosure = '"';
$_newline = '\r\n';
// Create the builder
$builder = new ViewBuilder;
$builder->layout = false;
$builder->setClassName('CsvView.Csv');
// Then the view
$view = $builder->build($data);
$view->set(compact('data', '_serialize', '_delimiter', '_enclosure', '_newline'));
// And Save the file
$file = new File('/full/path/to/file.csv', true, 0644);
$file->write($view->render());
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.