Latest Post

Download CSV file using php and Yii2 framework

I had the need to download a CSV file of my database so I could use it in gLabel to create address labels. There is an extension that adds this functionality to Yii2, but I didn’t need to add the complexity when the below code was sufficient. Add the code below to your view and then create a hyperlink to the action in your controller.

<?php

    if(count($models) > 0) {
        $delim = ',';
        $filename = "registered_users_" . date('Y-m-d');

        $f = fopen('php://memory', 'w');

        $fields = array('ID', 'Name', 'Address', 'Phone', 'Email');
        fputcsv($f, $fields, $delim);

        foreach($models as $model) {
            $line = array(
                $model['id'],
                $model['last_name'] . ', ' . $model['first_name'],
                $model['address'] . ' ' . $model['city'] . ', ' . $model['state'] . ' ' . $model['zip_code'],
                $model['phone_number'],
                $model['email']
            );
            fputcsv($f, $line, $delim);
        }

        fseek($f, 0);

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '";"');

        fpassthru($f);
    }
    exit;
?>