Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download CSV file from function in WordPress plugin?

Tags:

php

csv

wordpress

I've built a plugin for a client so that they can download data as a CSV file. It's been set up so that when the user clicks on a link in the menu, the CSV should just automatically download. However, it doesn't quite work like that, and just loads the function as a page in the WordPress backend.

This is the code I have for the function:

function download_payment_csv() {
    include 'lib/connection.php';

    $csv_output = '';

    $values = $db->query('SELECT * FROM tbPayments ORDER BY date DESC');

    $i=0;

    while ($rowr = mysql_fetch_row($values)) {
        for ($j=0;$j<$i;$j++) {
            $csv_output .= $rowr[$j].",";
        }
        $csv_output .= "\n";
    }

    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: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"report.csv\";" );
    header("Content-Transfer-Encoding: binary");

    echo $csv_output;

}

And as I said, it just returns a blank screen. Any help would be appreciated!

EDIT So this is the code I'm now working with, taking bits from what's been said already.

function download_payment_csv() {

    include 'lib/connection.php';

    $csv_output = '';

    $values = load_payment_csv();

    $fp = fopen("php://output", "w");

    $file = 'test_export';
    $filename = $file."_".date("Y-m-d_H-i",time());
    header("Content-Type: text/csv");
    header("Content-Disposition: attachment; filename=".$filename.".csv");
    // Disable caching
    header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1
    header("Pragma: no-cache"); // HTTP 1.0
    header("Expires: 0"); // Proxies
    header("Content-Transfer-Encoding: UTF-8");

    if(count($values) > 0) {
        foreach($values as $result) {
            fputcsv($fp, $result);
        }
    }

    fclose($fp);

}

This generates a CSV, but there is a problem with it.The problem is that when viewing the page it doesn't download it as a CSV, it just outputs the contents of the CSV in to the page. However, adding this function to the top of the plugin:

add_action('admin_init','download_payment_csv');

This then triggers a download when the menu link is clicked, which is fine. But it triggers it for every menu item in the plugin, which is wrong. It should only trigger when the download link is clicked.

like image 859
mickburkejnr Avatar asked Aug 14 '15 14:08

mickburkejnr


People also ask

How do I download a CSV file from WordPress?

To export WordPress data to CSV, Excel, or XML, go to WP All Export › New Export and select the type of data you'd like to export. Next, drag and drop the post data to set up your export file. Then run the export to create your customized WordPress export.

How do I download data from WordPress?

WordPress has a built-in export tool that lets you export your website. To use this, simply go to Tools » Export in your WordPress admin. Next, you need to select the 'All Content' option. This will export all your posts, pages, comments, custom fields, categories, tags, navigation menus, and custom posts.

How do I download a CSV file?

Go to File > Save As. Click Browse. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited). Note: The different formats support different feature sets.


Video Answer


1 Answers

/** * Query For Top Title Row */

$results = $wpdb->get_results("SHOW COLUMNS FROM $table" );
if(count($results) > 0){
    foreach($results as $result){
        $csv_output .= str_replace('_',' ',$result->Field).", "; // , or ;      
    }
}
$csv_output .= "\n";

/** * Query For All Required Data */

$results = $wpdb->get_results("SELECT * FROM $table",ARRAY_A );
if(count($results) > 0){
    foreach($results as $result){
        $result = array_values($result);
        $result = implode(", ", $result);
        $csv_output .= $result."\n"; 
    }
}

/** * Prepare Filename And CSV File to export */

$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;

Putting this all in a function should do the trick

like image 142
Kiran Avatar answered Sep 22 '22 11:09

Kiran