proloser/cakephp-csv

此软件包最新版本(2.0)没有可用的许可信息。

安装数: 18,927

依赖项: 0

建议者: 0

安全性: 0

星标: 52

关注者: 8

分支: 42

开放问题: 4

类型:cakephp-plugin

2.0 2018-11-25 05:37 UTC

This package is auto-updated.

Last update: 2024-09-08 19:20:21 UTC


README

允许将标准 $this->data 格式化的数组导入和导出至 csv 文件。目前不支持 HABTM。

选项

导入、导出和设置具有相同的选项和默认值

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

说明

  • 将行为添加到表中
<?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);
    }
}
?>

导入

  • 将 csv 文件上传到服务器

  • 将 csv 文件导入到您的数据变量中

方法 1: 使用第一行为 Model.field 头的 CSV 文件

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

方法 2: 将字段数组(按顺序)传递给方法

$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]);
    }
});

导出

  • 填充一个 $this->data 类型的数组
$data = $this->Post->find()->all();
  • 将数据导出到可写目录中的文件
$this->Posts->exportCsv($filepath, $data, $options);

附加可选回调函数

  • beforeImportCsv($filename, $fields, $options) 返回布尔值 $continue
  • afterImportCsv($data)
  • beforeExportCsv($filename, $data, $options) 返回布尔值 $continue
  • afterExportCsv()

常见问题解答

不正确的行结束符(OSX)

有些人 提到 有不正确的行结束符问题。这可以通过在您的 php 代码库中添加以下内容来解决

ini_set("auto_detect_line_endings", true);