Moodle php code : To get download report in multiple format

This will display the download option at page

echo $OUTPUT->download_dataformat_selector("Download",
        '/local/plugin/report.php', 'export');

Use following code to call the function

if ($export) {
    download_data($export);
    exit;
}

Function to download data in different format :

// dataform : csv/pdf/xls/html
function download_data($dataformat) {

    global $DB, $USER;
    if (ob_get_length()) {
        throw new coding_exception("Output can not be buffered before calling download_as_dataformat");
    }
    $classname = 'dataformat_' . $dataformat . '\writer';
    if (!class_exists($classname)) {
        throw new coding_exception("Unable to locate dataformat/$dataformat/classes/writer.php");
    }
    $format = new $classname;

    // The data format export could take a while to generate...
    set_time_limit(0);

    // Close the session so that the users other tabs in the same session are not blocked.
    \core\session\manager::write_close();

    // If this file was requested from a form, then mark download as complete (before sending headers).
    \core_form\util::form_download_complete();

    $columns = array(
    'First Name',
    'Last Name',
    
);
    $filename = date("dmY");
    $format->set_filename($filename);
    $format->send_http_headers();
    // This exists to support all dataformats - see MDL-56046.
    if (method_exists($format, 'write_header')) {
        $format->write_header($columns);
    } else {
        $format->start_output();
        $format->start_sheet($columns);
    }

        
        if ($users = $DB->get_records("users"))
        {
            $c=0;
            foreach ($users as $user)
            {
                $assigned_users[$usercontext->instanceid] = fullname($usercontext);
                $row = [];
                $row[] = $user->firstname;
                $row[] = $user->lastname;
                $format->write_record($row, $c++);
            }
        }

    if (method_exists($format, 'write_footer')) {
        $format->write_footer($columns);
    } else {
        $format->close_sheet($columns);
        $format->close_output();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *