Skip to content

Instantly share code, notes, and snippets.

@aziyan99
Forked from kralo/export-csv-moodle.php
Created December 28, 2022 09:45
Show Gist options
  • Save aziyan99/5d7c5e30f6081293961b2819f249f6f4 to your computer and use it in GitHub Desktop.
Save aziyan99/5d7c5e30f6081293961b2819f249f6f4 to your computer and use it in GitHub Desktop.
Example boilerplate for csv export from moodle
<?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