Created
August 13, 2014 08:45
-
-
Save kralo/293dbc07b9b318eabe43 to your computer and use it in GitHub Desktop.
Example boilerplate for csv export from moodle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Example for howto to serve a csv file for download in Moodle using the /lib/csvlib.class.php | |
* Very handy for exporting various data. This example demonstrates csv data export from within a moodle plugin | |
* | |
* This file is public domain where applicable, | |
* else GNU LGPL | |
*/ | |
require_once '../../config.php'; // to include $CFG, for example | |
require_once ($CFG->libdir . '/csvlib.class.php'); | |
// this is how you could make a button linking to this | |
// echo $OUTPUT->single_button(new moodle_url('/mod/modname/export_csv.php',array('id'=>$course->id)), get_string('download', 'admin')); | |
// You will want some parameters and login | |
// $id = required_param ( 'id', PARAM_INT ); // course id | |
// require_login ( $course ); | |
// $context = context_course::instance($id); | |
// require_capability('moodle/grade:export', $context); require_capability('gradeexport/txt:view', $context); | |
$downloadfilename = clean_filename ( "export_demo_csv" ); | |
$csvexport = new csv_export_writer ( 'semicolon' ); | |
$csvexport->set_filename ( $downloadfilename ); | |
$userdata = array ( | |
array ( | |
"person1", | |
"one", | |
"two" | |
), | |
array ( | |
"person2", | |
"three", | |
"four" | |
) | |
); | |
// Print names of all the fields | |
$fieldnames = array ( | |
'name', | |
'col1', | |
'col2' | |
); | |
$exporttitle = array (); | |
foreach ( $fieldnames as $field ) { | |
$exporttitle [] = $field; | |
} | |
// add the header line to the data | |
$csvexport->add_data ( $exporttitle ); | |
// Print all the lines of data. | |
foreach ( $userdata as $userline ) { | |
$csvexport->add_data ( $userline ); | |
} | |
// let him serve the csv-file | |
$csvexport->download_file (); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment