CSV view

Table of Contents 


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.


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],
            ['Camille', 31, 176],
        // set the file name (optional)
        $this['filename'] = 'userlist.csv';

        // set the used view
  • 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:

Previous: JSON view
Next: RSS view

Table of Contents