Csv

Open csv resource

Csv resource can be used to map data into a CSV format.

Example

Return multidimensional array (array[row][col]=value) as CSV file:

$this->get('csv')
    ->setFilename('myfile.csv')
    ->setData($dataArray)
    ->outputFile();

Write data to CSV file

Create $Csv. Then iterate through the set of pages and add selected values to csv data. Lastly, return data as csv file:

$Csv = $this->get('csv')->setFilename('testname.csv');

foreach ( $Pages as $Page ){
    $Csv->addRow(
        $Page->name,
        $Page->price
    );
}

$Csv->outputFile();

Setting the data one cell at a time:

foreach ( $Pages as $Page ){
    $Csv->newRow();
    $Csv->addColumn($Page->name);
    $Csv->addColumn($Page->price);
}

Setting delimiters. Default delimiter is ; and enclosure "

  $Csv->setDelimiter(',');
  $Csv->setEnclosure('"');

Setting colums:

  $Csv->addColumn('Määrä','number'); // value is formatted as number
  $Csv->addColumn('Päivä','date'); // value is formatted as date

  $Csv->addColumn(Array(
      'title' => 'Määrä',
      'type' => 'number',
      'hidden' => false // If TRUE, col is not added to file
  ));

Read data from CSV file

Set filename. File will be parsed when you ask data from it:

$data = $this->get('csv')->setFilename('testname.csv')->getData();

You can use additional parameters:

$Csv = $this->get('csv')
    ->setFilename('testname.csv')
    ->setDelimiter(',')
    ->setEnclosure('"')
    ->setLinebreak("CR");

$Data = $Csv->getData();

Full method list

Create

Method Return type Description
setFilename(string) this Set output filename.
getFilename() string Return the set output filename.
setDelimiter(string) this  Set cell delimiter, Default: ,
setEnclosure(string) this  Set cell enclosure, Default: "
setLinebreak(string) this  Set row linebreak, Default:
setCellbreak(string) this  Set linebreak inside cell data. Default: space
setLocale(string) this Set locale for date/number format
setColumns(array) this Clear columsn and add column definitions.
addColumn(string/array) this Set column definition

Set data

Method Return type Description
setContent(array) this Clear data and add data from two dimensional array.
addContent(array) this Add data from array.
clearContent() this Clear data.
setData(array) this Set 2-dimensional array.
addData(array) this Add 2-dimensional array
newRow() this Add new empty line.
addRow(array) this Add new row from array.
addRow(col1,col2,..) this Add new row from arguments.
addCell(data) this Add new cell to last line.

Get data

Method Return type Description
getData() array Return the data as two dimensional array.
getRowIndex() int Return the index of last row.
isRows() int Return TRUE if there are any data.
countRows() int Return number of lines.
countCols() int Return max number of cols.
getContent() string Return the csv content.
outputFile() void Send CSV file to browser.
saveToFile(filename) this Save data to file.