proloser/cakephp-csv 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

proloser/cakephp-csv

最新稳定版本:2.0

Composer 安装命令:

composer require proloser/cakephp-csv

包简介

README 文档

README

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

统计信息

  • 总下载量: 22.65k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 52
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 52
  • Watchers: 6
  • Forks: 41
  • 开发语言: PHP

其他信息

  • 授权协议: Unknown
  • 更新时间: 2015-08-07