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

mic*_*jnr 13 php csv wordpress

我为客户端构建了一个插件,以便他们可以将数据下载为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;

}
Run Code Online (Sandbox Code Playgroud)

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

编辑 所以这是我正在使用的代码,从已经说过的内容中取出一些代码.

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

}
Run Code Online (Sandbox Code Playgroud)

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

add_action('admin_init','download_payment_csv');
Run Code Online (Sandbox Code Playgroud)

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

小智 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";
Run Code Online (Sandbox Code Playgroud)

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

$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"; 
    }
}
Run Code Online (Sandbox Code Playgroud)

/***准备要导出的文件名和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;
Run Code Online (Sandbox Code Playgroud)

把这一切都放在一个函数中应该可以解决问题

  • 这是伟大的家伙:) (2认同)
  • 这很好,但是我收到错误消息,说无法修改标题信息? (2认同)

Pra*_*hak 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();
Run Code Online (Sandbox Code Playgroud)

  • 相当重要的安全问题......任何人都可以通过简单地猜测`download_report`参数来下载报告...... (4认同)

Han*_*och 3

您需要更改一些标头信息

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
Run Code Online (Sandbox Code Playgroud)

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

例如:

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

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

fclose($outstream);
exit();
Run Code Online (Sandbox Code Playgroud)

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

编辑:你还应该使用 $wpdb