CSV view


1Presentation

The CSV view allows sending CSV files made from PHP data.

By default, this is a simple stream (as for the JSON view) but, optionally, it is possible to specify a file name. The CSV will then be sent to the browser with instructions to treat it as an attachment and offer the user to save it to disk with the file name in question.

2Usage

Here is an example of sending data in CSV format:

class ApiController extends \Temma\Web\Controller {
    public function getUsers() {
        // recording of the data that will be sent
        // in the CSV stream
        $this['csv'] = [
            ['name', 'age', 'size'],
            ['Alice', 38, 162],
            ['Bob', 25, 184],
            ['John Doe', 31, 176],
        ];
        // set the file name (optional)
        $this['filename'] = 'userlist.csv';

        // set the used view
        $this->_view('\Temma\Views\Csv');
    }
}
  • Lines 5 to 9: The data to be sent in the CSV stream is defined by assigning them to the csv variable.
  • Line 11: We define the name of the CSV file (so that it is treated as an attachment) by assigning it to the filename variable.
  • Line 14: We specify that the view to use for the outgoing data is the CSV view (and not the usual Smarty view).

Note: The CSV view obviously does not need templates, since it is the PHP data that is directly serialized.

The received data will look like this:

name,age,size
Alice,38,162
Bob,25,184
"John Doe",31,176

3Separator

By default, the view separates fields in the generated CSV stream using the comma character (,). It is possible to use another character by passing it in the $separator template variable.

Here is an example using semicolons:

class ApiController extends \Temma\Web\Controller {
    public function getUsers() {
        // recording of the data that will be sent
        // in the CSV stream
        $this['csv'] = [
            ['name', 'age', 'size'],
            ['Alice', 38, 162],
            ['Bob', 25, 184],
            ['John Doe', 31, 176],
        ];
        // set the file name (optional)
        $this['filename'] = 'userlist.csv';

        // set the separator
        $this['separator'] = ';';

        // set the used view
        $this->_view('\Temma\Views\Csv');
    }
}

The received data will look like this:

name;age;size
Alice;38;162
Bob;25;184
"John Doe";31;176