PHP code example of friendsofcake / cakephp-csvview
1. Go to this page and download the library: Download friendsofcake/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/ */
// PostsController.php
// Add the CsvView class for content type negotiation
public function initialize(): void
{
parent::initialize();
$this->addViewClasses(['csv' => 'CsvView.Csv']);
}
// Controller action
public function index()
{
$posts = $this->Posts->find();
$this->set(compact('posts'));
if ($this->request->is('csv')) {
$serialize = 'posts';
$header = array('Post ID', 'Title', 'Created');
$extract = array('id', 'title', 'created');
$this->viewBuilder()->setOptions(compact('serialize', 'header', 'extract'));
}
}
// View used will be in templates/Posts/csv/export.php
public function export()
{
$posts = $this->Posts->find();
$this->set(compact('posts'));
$this->viewBuilder()
->setClassName('CsvView.Csv')
->setOption('serialize', null);
}