Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create 'Download to CSV' button from PHP array in Wordpress Admin

I have populated a multi-dimensional PHP array using a function and I wish to allow my admin users to download the content.

I've found a PHP function which should allow me to export an array to CSV and put it in my functions.php, used a second function to hook it to AJAX and used jQuery to fire the AJAX function.

What's the problem?

So I am 99% sure the AJAX correctly posts to the PHP function, but for some reason the download isn't being started.

I've researched this a lot but struggling to find a solution - would really appreciate a point in the right direction!

// Function to generate download

function convert_to_csv( $input_array, $output_file_name, $delimiter ) {
    /** open raw memory as file, no need for temp files, be careful not to run out of memory thought */
    $f = fopen( 'php://memory', 'w' );
    /** loop through array  */
    foreach ( $input_array as $line ) {
        /** default php csv handler **/
        fputcsv( $f, $line, $delimiter );
    }
    /** rewrind the "file" with the csv lines **/
    fseek( $f, 0 );
    /** modify header to be downloadable csv file **/
    header( 'Content-Type: application/csv' );
    header( 'Content-Disposition: attachement; filename="' . $output_file_name . '";' );
    /** Send file to browser for download */
    fpassthru( $f );
}

And I've hooked it to Wordpress AJAX using another function

function laura_function() {

    $input_array = $_POST["inputarray"];

    convert_to_csv($input_array, 'output.csv', ',');

    exit;

}
add_action('wp_ajax_nopriv_ajaxlaurafunction', 'laura_function');
add_action('wp_ajax_ajaxlaurafunction', 'laura_function');

And I've written a little jQuery Function to make the AJAX call on button click

<button type="button" id="downloadcsv">Download CSV</button>

<script>

    jQuery(document).ready(function () {
        jQuery('#downloadcsv').click(function () {

        var data = {
            action: 'ajaxlaurafunction', // Calls PHP function - note it must be hooked to AJAX
           inputarray: '<?php echo $inputarray?>', // Sends a variable to be used in PHP function
        };

        // This is a shortened version of: https://api.jquery.com/jquery.post/

        jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data, function () {
            //window.location.replace(location.pathname)
        });

    });
});

like image 325
LauraTheExplorer Avatar asked Dec 03 '22 21:12

LauraTheExplorer


1 Answers

Following on from @charlietfl suggestion I have found that "you can't do it through Ajax because JavaScript cannot save files directly to a user's computer (out of security concerns). - According to this post"

Alternative Solution

My alternative solution is to use a 'post method' to set a post parameter.

// Form on Page 
<form method="post" id="download_form" action="">
    <input type="submit" name="download_csv" class="button-primary" value="Download CSV" />
</form>

And this code runs if the 'download_csv' parameter has been posted, to download the data. At the moment my code will output dummy data, but I am working on that.

add_action("admin_init", "download_csv");

function download_csv() {

if (isset($_POST['download_csv'])) {

    function outputCsv( $fileName, $assocDataArray ) {
        ob_clean();
        header( 'Pragma: public' );
        header( 'Expires: 0' );
        header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
        header( 'Cache-Control: private', false );
        header( 'Content-Type: text/csv' );
        header( 'Content-Disposition: attachment;filename=' . $fileName );
        if ( isset( $assocDataArray['0'] ) ) {
            $fp = fopen( 'php://output', 'w' );
            fputcsv( $fp, array_keys( $assocDataArray['0'] ) );
            foreach ( $assocDataArray AS $values ) {
                fputcsv( $fp, $values );
            }
            fclose( $fp );
        }
        ob_flush();
    }

    // This is dummy data. 

    $data = array(
        array( 'item' => 'Server', 'cost' => 10000, 'approved by' => 'Joe' ),
        array( 'item' => 'Mt Dew', 'cost' => 1.25, 'approved by' => 'John' ),
        array( 'item' => 'IntelliJ IDEA', 'cost' => 500, 'approved by' => 'James' ),
    );


    outputCsv( 'expenses.csv', $data );

    exit; // This is really important - otherwise it shoves all of your page code into the download

}

}
like image 128
LauraTheExplorer Avatar answered Dec 06 '22 12:12

LauraTheExplorer