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

[eluser]ufasoli[/eluser]
Hi,
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

Ulises
#2

[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.
#3

[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.
#4

[eluser]ufasoli[/eluser]
Hi Again,
I ended up doing it like Craig suggested. This is how I do it :

Controller File :

Code:
function exportedToCSV()
    {
        $this->load->dbutil();
        $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
Code:
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..
#5

[eluser]See64[/eluser]
What about just this?

Code:
$this->load->dbutil();
        $this->load->helper('download');
        
        $query = $this->db->query("SELECT * FROM `table`");
        $data = $this->dbutil->csv_from_result($query, ';');
        
        force_download('result.csv', $data);
#6

[eluser]ufasoli[/eluser]
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