Skip to content

A component that will import data from a csv file. Other features for the plugin may come later.

Notifications You must be signed in to change notification settings

gmccrackin/CakePHP-CSV

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 

Repository files navigation

CSV Plugin

Allows the importing and exporting of a standard $this->data formatted array to and from csv files. Doesn't currently support HABTM. I may remove the component now that I created the behavior instead.

Options

Importing, exporting and setup come with the same options and default values

$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,
)

Component Instructions

  1. Add Component to controller
var $components = array('Csv.Csv' => $options);

Importing

  1. Upload a csv file to the server

  2. Import the csv file into your data variable

Approach 1: Use a CSV file with the first row being Model.field headers

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->Csv->import($content, $options);

Approach 2: Pass an array of fields (in order) to the method

$this->data = $this->Csv->import($content, array('Post.title', 'Post.created', 'Post.modified', 'body', 'user_id', 'Category.0.name', 'Category.0.description', 'Category.1.name', 'Category.1.description'));
  1. Process/save/whatever with the data
$this->Post->saveAll($this->data);

Exporting

  1. Populate an $this->data type array
$data = $this->Post->find('all', array('recursive' => 0));
  1. Export to a file in a writeable directory
$this->Csv->export($filepath, $data, $options);

Behavior Instructions

The instructions are identical to the component, except for a few method name changes and additional callbacks

  1. Add Behavior to the model
var $components = array('Csv.Csv' => $options);
  1. Upload a csv file to the server

  2. Follow instruction for the component, Import using $this->importCsv() and export with $this->exportCsv()

  3. Additional optional callbacks:

    • beforeImportCsv($filename, $fields, $options) returns boolean $continue
    • afterImportCsv($data)
    • beforeExportCsv($filename, $data, $options) returns boolean $continue
    • afterExportCsv()

About

A component that will import data from a csv file. Other features for the plugin may come later.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published