Download CSV File - Moodle 2.9.4

Download CSV File - Moodle 2.9.4

by Dave Emsley -
Number of replies: 2

Hi there,

I'm developing a block and it works fine on both my testing and production servers.  However there is an issue with one part of the code.  I am downloading an associated array as a CSV file.

Works fine on the testing server but not on the hosted production server.  On the production server I get screen output.

Two questions:

Is there any issue with my code?  As I say works on the testing server so think it's OK:

                if(isset($associated_array['0'])){
                    ob_clean();
                    $fp = fopen('php://output', 'w');
 
                    if (!$fp) { die("unable to open file for output"); }            
                    fputcsv($fp, array_keys($associated_array['0']));
                    foreach($associated_array AS $values){
                        fputcsv($fp, $values);
                    }
                    $string=ob_get_clean();
                    header('Content-Type: application/octet-stream');
                    header('Content-Disposition: attachment;filename="export.csv"'); 
                    fclose($fp);
                    ob_flush();
                    exit($string);   
                }


The second question is are there any CSV based library functions in Moodle to do this and therefore guarantee it works.


Cheers


Dave Emsley



Average of ratings: -
In reply to Dave Emsley

Re: Download CSV File - Moodle 2.9.4

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

Have you tried lib/csvlib.class.php? (A quick search for 'fputcsv' should have located that pretty quickly in the code).


Average of ratings: Useful (1)
In reply to Davo Smith

Re: Download CSV File - Moodle 2.9.4

by Dave Emsley -
So anyway here's the code I should have used:

require_once("$CFG->libdir/csvlib.class.php");//At top of file.


$myfile = new csv_export_writer();
$dlfile = $myfile->download_array('EnrolmentKeys',$associated_array);

Many thanks to Davo for pointing me in the right direction and, of course, to Petr Skoda the author fo the library package.  The more I get into the coding the easier it seems to become as others have already been there and done that.

So this code now works on the testing server. However I still get the same issue on the production server in that it is pushed to the screen.

Cheers

Dave Emsley