Export to CSV, XML & JSON – Then Stream, Save or Display

Published on by Safeer

More often then not as a developer you’ll find that you have to output data to XML, CSV, JSON, this could be a simple method to export data for external processing or a way to backup data. Obviously you could manually create the boilerplate code – but that’s cumbersome especially when there are packages available to help you export data to another format. I’ll be showing how to easily export data, so to get started with it just add the following line to your composer.json

        "sonata-project/exporter": "1.2.2"

Then update your composer packages by running composer update. Once this is done you can start using the exporter package. To do so you need to first pick a Exporter Source, this can one of the following:

  1. Array
  2. Doctrine
  3. PDO

However for this article we’ll just be using an Array, so just pick the ArraySourceIterator, and this can be setup by adding the following line of code:

        //  The data to export
        $data = array(
            0 => array(
                'name' => 'Jack'
            ),
            1 => array(
                'name' => 'Jill'
            )
        );

        // We're adding an Array to the Array Source Iterator
        $exporter_source = new \Exporter\Source\ArraySourceIterator($data);

Next it’s time to pick the output format, the following output writers are available:

  1. CSV
  2. XML
  3. JSON
  4. Sitemap
  5. XLS
  6. Google Search Appliance
  7. In Memory

For this article we’ll just use the CSV writer, however you can change this to one of the other writers including JSON or XML writer. So to use the CSV writer just add the following lines of code:

        // Location to Export this to
        $export_to = 'file location to save the exported data';

        // Get an Instance of the CSV Writer
        $exporter_writer = new \Exporter\Writer\CsvWriter($export_to);

Now all you need to do is call:

        // Export to the format
        \Exporter\Handler::create($exporter_source, $exporter_writer)->export();

This in turn will export your supplied data in the format you choose. As we’ve used a library to switch the format we’re now able to use a standard way to swap formats, i.e. if we wanted to output the data to JSON or XML we could replace the writer from CSV to JSON/XML by:

        // Get an Instance of the JSON Writer
        $exporter_writer = new \Exporter\Writer\JsonWriter($export_to);

        // Get an Instance of the XML Writer
        $exporter_writer = new \Exporter\Writer\XmlWriter($export_to);

As you can see by changing one line we’re able to access different formats. In addition to this we can create our own Writer by creating a class that implements the Exporter\Writer\WriterInterface interface.

As the above would expect to save the data to disk, if we wanted to display this data we could set the $export_to location as

        $export_to = 'php://output';

This would then use one of the PHP I/O Output Streams, this one in particular writes to the output buffer in the same way as print/echo does. We would also need to set the right Content-type headers before calling \Export\Handler.

Now if we wanted this to stream to the end user as a file we would need the following headers to be set as well:

        header('Content-Description: File Transfer');
        header('Content-Disposition: attachment; filename=file.csv;');

As you can see by using a library we’re able to switch between formats with ease while keeping our codebase clean and easier to expand on. Below I’ve added source code which shows how to Export & Save, Export & Output and Export & Stream.

Export & Save

        // Pick a format to export to
        $format = 'csv';

        // Filename
        $filename = 'test-file';

        // Set Content-Type
        $content_type = 'text/csv';

        // Location to Export this to
        $export_to = 'file location' . $filename;

        // Data to export
        $exporter_source = new \Exporter\Source\ArraySourceIterator($data);

        // Get an Instance of the Writer
        $exporter_writer = '\Exporter\Writer\\' . ucfirst($format) . 'Writer';

        $exporter_writer = new $exporter_writer($export_to);

        // Export to the format
        \Exporter\Handler::create($exporter_source, $exporter_writer)->export();

Export & Output

        // Pick a format to export to
        $format = 'csv';

        // Set Content-Type
        $content_type = 'text/csv';

        // Location to Export this to
        $export_to = 'php://output';

        // Data to export
        $exporter_source = new \Exporter\Source\ArraySourceIterator($data);

        // Get an Instance of the Writer
        $exporter_writer = '\Exporter\Writer\\' . ucfirst($format) . 'Writer';

        $exporter_writer = new $exporter_writer($export_to);

        // Set the right headers
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Content-type: ' . $content_type);
        header('Expires: 0');
        header('Pragma: public');

        // Export to the format
        \Exporter\Handler::create($exporter_source, $exporter_writer)->export();

Export & Stream

        // Pick a format to export to
        $format = 'csv';

        // Filename
        $filename = 'test-file';

        // Set Content-Type
        $content_type = 'text/csv';

        // Location to Export this to
        $export_to = 'php://output';

        // Data to export
        $exporter_source = new \Exporter\Source\ArraySourceIterator($data);

        // Get an Instance of the Writer
        $exporter_writer = '\Exporter\Writer\\' . ucfirst($format) . 'Writer';

        $exporter_writer = new $exporter_writer($export_to);

        // Set the right headers
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Content-Description: File Transfer');
        header('Content-type: ' . $content_type);
        header('Content-Disposition: attachment; filename=' . $filename . ';');
        header('Expires: 0');
        header('Pragma: public');

        // Export to the format
        \Exporter\Handler::create($exporter_source, $exporter_writer)->export();