如何从WordPress插件中的功能下载CSV文件?

时间:2015-08-14 14:27:10

标签: php wordpress csv

我为客户构建了一个插件,以便他们可以将数据下载为CSV文件。它已经设置好,当用户点击菜单中的链接时,CSV应该只是自动下载。但是,它并不像那样工作,只是将函数作为WordPress后端的页面加载。

这是我对该函数的代码:

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;

}

正如我所说,它只是返回一个空白屏幕。任何帮助将不胜感激!

修改 所以这就是我现在正在使用的代码,从已经说过的内容中提取一些内容。

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);

}

这会生成CSV,但是存在问题。问题是,在查看页面时,它不会将其作为CSV下载,它只会将CSV的内容输出到页面中。但是,将此函数添加到插件的顶部:

add_action('admin_init','download_payment_csv');

然后在单击菜单链接时触发下载,这很好。但是它会为插件中的每个菜单项触发它,这是错误的。它应该仅在单击下载链接时触发。

4 个答案:

答案 0 :(得分:12)

/ **  *查询最高标题行  * /

$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";

/ **  *查询所有必需的数据  * /

$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"; 
    }
}

/ **  *准备要导出的文件名和CSV文件  * /

$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;

将这一切都放在一个函数中应该可以做到这一点

答案 1 :(得分:7)

试试这个:

<?php

class CSVExport
{
/**
 * Constructor
 */
public function __construct()
{
    if(isset($_GET['download_report']))
    {
        $csv = $this->generate_csv();

        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;
        exit;
    }

    // Add extra menu items for admins
    add_action('admin_menu', array($this, 'admin_menu'));

    // Create end-points
    add_filter('query_vars', array($this, 'query_vars'));
    add_action('parse_request', array($this, 'parse_request'));
}

/**
 * Add extra menu items for admins
 */
public function admin_menu()
{
    add_menu_page('Download Report', 'Download Report', 'manage_options', 'download_report', array($this, 'download_report'));
}

/**
 * Allow for custom query variables
 */
public function query_vars($query_vars)
{
    $query_vars[] = 'download_report';
    return $query_vars;
}

/**
 * Parse the request
 */
public function parse_request(&$wp)
{
    if(array_key_exists('download_report', $wp->query_vars))
    {
        $this->download_report();
        exit;
    }
}

/**
 * Download report
 */
public function download_report()
{
    echo '<div class="wrap">';
    echo '<div id="icon-tools" class="icon32"></div>';
    echo '<h2>Download Report</h2>';
    //$url = site_url();

    echo '<p><a href="site_url()/wp-admin/admin.php?page=download_report&download_report">Export the Subscribers</a>';
}

/**
 * Converting data to CSV
 */
public function generate_csv()
{
    $csv_output = '';
    $table = 'users';

    $result = mysql_query("SHOW COLUMNS FROM ".$table."");

    $i = 0;
    if (mysql_num_rows($result) > 0) {
        while ($row = mysql_fetch_assoc($result)) {
            $csv_output = $csv_output . $row['Field'].",";
            $i++;
        }
    }
    $csv_output .= "\n";

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

    return $csv_output;
}
}

// Instantiate a singleton of this plugin
$csvExport = new CSVExport();

答案 2 :(得分:2)

您需要更改一些标题信息

header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename="report.csv"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0

之后使用php://输出直接向浏览器提供数据,这将阻止空白页。

例如:

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

foreach($result as $result)
{
    fputcsv($outstream, $result);
}

fclose($outstream);
exit();

php:// output是一个只读流,允许您直接向请求者提供数据。

编辑:你也应该使用$ wpdb

答案 3 :(得分:0)

这是我找到的解决方案,当在网站的前端使用时,在输出 HTML 代码时遇到了很多麻烦。关键是将退出交换为“死”。这是我在自己的网站上使用的代码。


header('Content-Type: text/csv');
$FileName = 'Content-Disposition: attachment; filename="'. 'Report.csv"';
header($FileName);

$fp = fopen('php://output', 'w');
    
$header_row = array(
        0 => 'data1',
        1 => 'data2',
        2 => 'data3',
    );
fputcsv($fp, $header_row); 

$rows = GetDataBaseData();
if(!empty($rows)) 
  {
   foreach($rows as $Record)
     {      
    // where data1, data2, data3 are the database column names 
    $OutputRecord = array($Record['data1'], $Record['data1'], $Record['data1']);
    fputcsv($fp, $OutputRecord);         
    }
    unset($rows);
  }

fclose( $fp );
    
die;   <===== key point.  Use DIE not Exit.  Exit will only work on the back end. Die will work on both.
```

Works on the front and backend of wordpress.