mehrshaddarzi
10/10/2018 - 6:19 AM

force download and csv

force download and csv

<?php

/**
     * Check Exist User With Mobile Meta data
     *
     * @param array  $data Mobile Number
     * @param string  $filename File Name
     * @return string export Force Download Csv File
     */
    public function create_csv($data, $filename)
    {
        $filepath = $_SERVER["DOCUMENT_ROOT"] . $filename.'.csv';
        $fp = fopen($filepath, 'w+');

        $i = 0;
        foreach ($data as $fields) {
            if($i == 0){
                fputcsv($fp, array_keys($fields));
            }
            fputcsv($fp, array_values($fields));
            $i++;
        }
        header('Content-Type: application/octet-stream; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
        header('Content-Length: ' . filesize($filepath));
        echo file_get_contents($filepath);
        exit;
    }
add_action( 'admin_init', array( $this, 'create_csv' ) );


//Another Page
https://stackoverflow.com/questions/21576870/force-file-download-inside-a-wordpress-plugin
https://www.kirstencassidy.com/download-pdf-in-wordpress/
https://stackoverflow.com/questions/27888374/create-csv-and-force-download-of-file