csvexport Create CSV string or write CSV to file from record set

  1. Requirements
  2. Usage

New Rewritten version! Class renamed as well. Download had incorrect folder name and file name, though the class itself is named correctly. Don't code late at night.

  • fixed csql bug (Timbo)
  • updated when exportFull is true and CActiveDataProvider has pagination set. It now properly turns it off.
  • update headers bug/var ref error (lunatic77)
  • fixed row exclude bug
  • updated to fix runtime enclosure/delimiter being set in toCSV()

CSVExport will allow you to create a csv file with optional row callbacks. By default it will return a string of comma delimited items, but can also write a file if you need one.

By passing an Array, CDbCommand, CSqlDataProvider, or CActiveDataProvider instance this extension will create a csv string or file, taking into account also any paging settings.

For extremely large csv files, you should just use mysql's select into file instead, as it will be really fast (you just need correct permissions).

Requirements

Yii 1.1 PHP 5.2+

Usage

Delimiter and Enclosure defaults to php defaults of , and ". You can change this with set functions, or at the call toCSV(). Many set* functions provide a fluent interface as well.

Yii::import('ext.ECSVExport');

// for use with array of arrays
$data = array(
    array('key1'=>'value1', 'key2'=>'value2')
    ....
)

$csv = new ECSVExport($data);
$output = $csv->toCSV(); // returns string by default

echo $output;

// gives you something like
key1,key2
value1,value2

// OR
$csv = new ECSVExport($provider);
$content = $csv->toCSV();					
Yii::app()->getRequest()->sendFile($filename, $content, "text/csv", false);
exit();

Writing To File

Yii::import('ext.ECSVExport');

// for use with array of arrays
$data = array(
    array('key1'=>'value1', 'key2'=>'value2')
    ....
)

$filename = 'somewriteablefile.csv';
$csv = new ECSVExport($data);
$csv->toCSV($filename); // returns string by default

echo file_get_contents($filename);

// gives you something like
key1,key2
value1,value2

Human Readable headers

$headers = array('header_to_change'=>'new value');
$csv->setHeaders($headers);

// or

$csv->setHeader($currentHeaderValue, $newHeaderValue);

Per Row Callback

// callback must be is_callable by php or exception is thrown

$csv->setCallback(function($row){
    $new = array();
    foreach($row as $k=>$v) {
        $new[$k] = $v * $v;
    }
    return $new;
});

Exclude Columns

$exclude = array('getlost','dontshow'...);
$csv->setExclude($exclude);

// or

$csv->setExclude($nameofcolumn);

Various Provider types

// CDbCommand
$cmd = Yii::app()->db->createCommand("SELECT * FROM track_test LIMIT 10");
$csv = new ECSVExport($cmd);        
$csv->setOutputFile($outputFile);
$csv->toCSV();

// CSqlDataProvider
// Defaults to looping through all pages, use $csv->exportCurrentPageOnly(); to turn that off
$count=Yii::app()->db->createCommand('SELECT COUNT(*) FROM track_test WHERE campaign_id=1')->queryScalar();
$sql='SELECT * FROM track_test WHERE campaign_id=1';
$dataProvider=new CSqlDataProvider($sql, array(
    'totalItemCount'=>$count,
    'pagination'=>array(
        'pageSize'=>10,
    ),
));

$csv = new ECSVExport($dataProvider);
$csv->exportCurrentPageOnly(); // if not set will loop through all pages!
$csv->setOutputFile($this->outputFile);
$csv->toCSV();

// CActiveDataProvider
$dataProvider = new CActiveDataProvider('Track', array(
    'criteria'=>array(
        'condition'=>'campaign_id=1 and type=1'
    )
));
$csv = new ECSVExport($dataProvider);
$csv->setOutputFile($this->outputFile);
$csv->toCSV();

// Active Records
$csv = new ECSVExport(Track::model()->findAllByAttributes(array('campaign_id'=>1,'type'=>Track::TYPE_INT_SUCCESS)));
$csv->setOutputFile($this->outputFile);
$csv->toCSV();

When working with CActiveDataProviders, you can often run out of memory when working with large resultsets. $convertActiveDataProvider defaults to true, which creates a command out of provider. While this seems to fix memory problems, you are no longer able to use the with() function and will will to resort to joins. Sorry! Use dontConvertProvider() to turn that off.

24 0
40 followers
6 786 downloads
Yii Version: 1.1
License: BSD-2-Clause
Category: Database
Developed by: nsbucky
Created on: Jan 22, 2011
Last updated: 4 years ago

Downloads

show all

Related Extensions