Welcome Guest, Not a member yet? Register   Sign In
Creating then Sending a .csv file to a user

I'm using code Igniter to get some data from the database and then show it on the screen in a table and that works fine. My boss wants to be able to export this data into a .csv file. What I really want to do with it is create the file on request but instead of saving the file on the server pop-up a dialog so the user can store it in his own computer like when you download a file from somewhere... any ideas to how to do this?? can I do it with Code-Igniter??

Thanks in advance


[eluser]Craig A Rodway[/eluser]
I think there are two ways you could do this. Either get it to generate a file that is saved on to a web-accessible part of the server and give the user a link to download it. Or... hyperlink to a controller function that outputs the CSV data - but use PHP header() function to set content type to text/csv (off the top of my head) which should tell the browser to download it rather than just view the data.

[eluser]Derek Allard[/eluser]
What about $this->dbutil->csv_from_result($db_result). Would that work for you?

You'd then need the file helper to set up the file for download.

Hi Again,
I ended up doing it like Craig suggested. This is how I do it :

Controller File :

function exportedToCSV()
        $delimiter = ";";
        $newline = "\r\n";
        $result = $this->db->query($this->session->userdata('lastQuery'));
        $this->load->view('exportedToCsv', array('csv'=> $this->dbutil->csv_from_result($result, $delimiter, $newline)));

View file
header("Content-type: application/csv-tab-delimited-table" );
           header("Content-Disposition: attachment filename=\"export.csv\"" );
           header("Content-Description: fichier binaire" );
           header("Content-Transfer-Encoding: binary" );
           echo $csv;

Works like a charm

Thanks a lot you guys..

What about just this?

        $query = $this->db->query("SELECT * FROM `table`");
        $data = $this->dbutil->csv_from_result($query, ';');
        force_download('result.csv', $data);

actually this one did it better, as with the previous solution sometimes the file extension wasn't present, thank you very much Wink

Theme © iAndrew 2016 - Forum software by © MyBB