Giter VIP home page Giter VIP logo

cakephp-csv's Introduction

CSV Plugin

Allows the importing and exporting of a standard $this->data formatted array to and from csv files. Doesn't currently support HABTM.

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

Instructions

  • Add Behavior to the table
<?php
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);
    }
}
?>

Importing

  • Upload a csv file to the server

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

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

$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'));
  • Process/save/whatever with the data
$entities = $this->Posts->newEntities($data);
$Table = $this->Posts;
$Table->connection()->transactional(function () use ($Table, $entities) {
    foreach ($entities as $entity) {
        $Table->save($entity, ['atomic' => false]);
    }
});

Exporting

  • Populate an $this->data type array
$data = $this->Post->find()->all();
  • Export to a file in a writeable directory
$this->Posts->exportCsv($filepath, $data, $options);

Additional optional callbacks:

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

FAQ

Incorrect Line Endings (OSX)

Some people have mentioned having incorrect line endings. This can be fixed by having this in your php codebase:

ini_set("auto_detect_line_endings", true);

cakephp-csv's People

Contributors

challgren avatar emacaste avatar jacopkane avatar krecik avatar paulleephp avatar proloser avatar ravage84 avatar rochamarcelo avatar webnard avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cakephp-csv's Issues

I am unable to Export CSV it is returning false

I am trying to Export a file at a custom location in a webroot directory, for that purpose I am using $this->Csv->export($path, $data); but this method is returning 'False'. Do I need to create a Csv file in order to export data or the export method itself creates the file and exports data?

Please suggest the steps to rectify this problem. Thanks

Helper Class Missing

$this->Csv->export($filePath, $data);

The above line shows error app/View/Heper/CSVHelper class missing. The file is getting created but not auto-downloading
I am using cakephp 2.x

Naming

The namespace name is not ideal IMO.
Please consider the following recommendation in such cases:

CakeCsv\\": "src/",

etc

CSV Export

I am trying to export data into .csv format, and it gets the below error:
iconv(): Detected an illegal character in input string

In CsvComponent on line 44 i.e. the return iconv()
protected function _encode($str = '') {
return iconv("UTF-8", "WINDOWS-1257", html_entity_decode($str, ENT_COMPAT, 'utf-8'));
}

How do I install the plug-in?

How do I install the plug-in?
cakephp 3 plugins in the plugin was downloaded copy.
And I added the following code to initialize method to fooTable.php.

$ 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,
         );
         $ this-> addBehavior ('CakePHPCSV.Csv', $ options);

Running comes the following error:

CakePHPCSV.CsvBehavior could not be found.

Make sure your plugin CakePHPCSV is in the / var / www / source / plugins / directory and was loaded.

composer not found CakePHP-CSV

Unable to add in Plugin Folder

Missing Plugin
Cake\Core\Exception\MissingPluginException
Documentation API
Error: The application is trying to load a file from the CakePHPCSV plugin.

Make sure your plugin CakePHPCSV is in the D:\xampp\htdocs\cakephp\plugins\ directory and was loaded.

Number of rows to skip

I think it will be a good enhancement. Consider a situation where a CSV template is used with headers in top few rows (for sake of example, top 1 row) to perform bulk upload on some model. This option will come very handy - I have it in my own work to do CSV import.

Anyways, a simple and effective way of doing it can be something like (there are many possible alternatives):

public $defaults = array(
        'length' => 0,
        'delimiter' => ',',
        'enclosure' => '"',
        'escape' => '\\',
        'headers' => true,
        'skiprows' => 1     // number of rows to skip from beginning
    );

Note the additional entry skiprows.

Then in your import():

while ($row = fgetcsv($file, $options['length'], $options['delimiter'], $options['enclosure'])) {
                if($r < $options['skiprows']) {   // added this condition
                    $r++; continue;   // don't forget to do r++
                }
                // for each header field
                foreach ($fields as $f => $field) {
                    ...
                }
                r++;
            }
            ...
        }
        ...
    }

var_dump($value);

into file vendor\proloser\cakephp-csv\src\Model\Behavior\CsvBehaviore at row 142 there is var_dump($value);

Is a debug line?

thanks

Line endings Macintosh

If you are uploading a CSV created on a Mac you may have issues with it not detecting line endings correctly.
I fixed this by adding the following to the initialize method in the component:

ini_set("auto_detect_line_endings", true);

CakePHP version

Reckon you could adjust the ReadMe to mention what versions of CakePHP it's compatible with? It would make it easier to judge suitability at a glance. Thanks.

install composer

Hello , can you give us the url to install CakePHP-CSV through composer ?

thanks

Inport data

I can not use the method "import", it always returns "false"
this is my code:

if($this->request->is('post')){
    $content = file_get_contents($this->request->data["csv"]["tmp_name"]);
    file_put_contents(WWW_ROOT."files".DS."{$this->request->data["csv"]["name"]}", $content);
    $fields = array(
        "Model.colum",
        "Model.colum",
        "Model.colum",
        "Model.colum"
    );
// attempt1     $this->data = $this->Csv->import($this->request->data["csv"]["tmp_name"], $fields);
// attempt2     $this->data = $this->Csv->import($content, $fields);
// attempt3     $this->data = $this->Csv->import(WWW_ROOT."files".DS."{$this->request->data["csv"]["name"]}", $fields);
    debug($this->data);
    echo '<pre>';var_dump($this->data);echo '</pre>';
            
}




How to remove the array key that having empty space?

Dear Friends,

After I successfully fetch the data from CSV file, if the CSV file header having space (Ex: Created Date), then the array key also [created data], so how I can make the array key as [created_date] even if there is space in the headers of CSV?

Array                                            
(                                                
    [0] => Array                                 
        (                                        
            [created date] => 09-05-2018         
            [indicator] => I                     
            [material_division_code] => 001      
            [material_group_code] => 11003       
            [material_code] => 1500001           
            [description] => COOLGALE 48 COPPER  
            [material_type] => RM                
            [hsn_sac] => 9954                    
            [uom] => KG                          
            [net_weight] => 0                    
            [gross_weight] => 0                  
            [volume] => 100                      
            [volume_unit] => M3                  
            [diamention] => 10 x 12 x 2          
            [part_no] => 33856                   
            [lot_no] => 50                       
        )                                         
)              

Passing $model as reference in setup() function

Is there a particular reason why $model is being passed as reference in setup() in CsvBehavior?
I'm using PHP 5.5 and CakePHP 2.5.4 and I would get error like:

Strict Error: Declaration of CsvBehavior::setup() should be compatible with ModelBehavior::setup(Model $model, $config = Array)

unless I remove the reference operator from the setup function.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.