PHP code example of proloser / cakephp-csv

1. Go to this page and download the library: Download proloser/cakephp-csv 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/ */

    

proloser / cakephp-csv example snippets


$options = array(
	// Refer to php.net fgetcsv for more information
	'length' => 0,
	'delimiter' => ',',
	'enclosure' => '"',
	'escape' => '\\',
	// Generates a Model.field headings row from the csv file
	'headers' => true,
	// If true, String $content is the data, not a path to the file
	'text' => false,
)


namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\Table;

/**
 * Posts Model
 */
class PostsTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        //$options = ...
        $this->addBehavior('CakePHPCSV.Csv', $options);
    }
}

Posts.csv
Post.title, Post.created, Post.modified, body, user_id, Section.name, Category.0.name, Category.0.description, Category.1.name, Category.1.description
..., ..., ...

$this->data = $this->Posts->import($content, $options);

$data = $this->Posts->import($content, array('Post.title', 'Post.created', 'Post.modified', 'body', 'user_id', 'Category.0.name', 'Category.0.description', 'Category.1.name', 'Category.1.description'));

$entities = $this->Posts->newEntities($data);
$Table = $this->Posts;
$Table->connection()->transactional(function () use ($Table, $entities) {
    foreach ($entities as $entity) {
        $Table->save($entity, ['atomic' => false]);
    }
});

$data = $this->Post->find()->all();

$this->Posts->exportCsv($filepath, $data, $options);

ini_set("auto_detect_line_endings", true);